"use strict";
/*
 * ATTENTION: The "eval" devtool has been used (maybe by default in mode: "development").
 * This devtool is neither made for production nor for readable output files.
 * It uses "eval()" calls to create a separate source file in the browser devtools.
 * If you are trying to read the output file, select a different devtool (https://webpack.js.org/configuration/devtool/)
 * or disable the default devtool with "devtool: false".
 * If you are looking for production-ready output files, see mode: "production" (https://webpack.js.org/configuration/mode/).
 */
(self["webpackChunk_JUPYTERLAB_CORE_OUTPUT"] = self["webpackChunk_JUPYTERLAB_CORE_OUTPUT"] || []).push([["vendors-node_modules_codemirror_view_dist_index_js"],{

/***/ "../node_modules/@codemirror/view/dist/index.js":
/*!******************************************************!*\
  !*** ../node_modules/@codemirror/view/dist/index.js ***!
  \******************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */   BidiSpan: () => (/* binding */ BidiSpan),\n/* harmony export */   BlockInfo: () => (/* binding */ BlockInfo),\n/* harmony export */   BlockType: () => (/* binding */ BlockType),\n/* harmony export */   Decoration: () => (/* binding */ Decoration),\n/* harmony export */   Direction: () => (/* binding */ Direction),\n/* harmony export */   EditorView: () => (/* binding */ EditorView),\n/* harmony export */   GutterMarker: () => (/* binding */ GutterMarker),\n/* harmony export */   MatchDecorator: () => (/* binding */ MatchDecorator),\n/* harmony export */   RectangleMarker: () => (/* binding */ RectangleMarker),\n/* harmony export */   ViewPlugin: () => (/* binding */ ViewPlugin),\n/* harmony export */   ViewUpdate: () => (/* binding */ ViewUpdate),\n/* harmony export */   WidgetType: () => (/* binding */ WidgetType),\n/* harmony export */   __test: () => (/* binding */ __test),\n/* harmony export */   closeHoverTooltips: () => (/* binding */ closeHoverTooltips),\n/* harmony export */   crosshairCursor: () => (/* binding */ crosshairCursor),\n/* harmony export */   drawSelection: () => (/* binding */ drawSelection),\n/* harmony export */   dropCursor: () => (/* binding */ dropCursor),\n/* harmony export */   getDrawSelectionConfig: () => (/* binding */ getDrawSelectionConfig),\n/* harmony export */   getPanel: () => (/* binding */ getPanel),\n/* harmony export */   getTooltip: () => (/* binding */ getTooltip),\n/* harmony export */   gutter: () => (/* binding */ gutter),\n/* harmony export */   gutterLineClass: () => (/* binding */ gutterLineClass),\n/* harmony export */   gutters: () => (/* binding */ gutters),\n/* harmony export */   hasHoverTooltips: () => (/* binding */ hasHoverTooltips),\n/* harmony export */   highlightActiveLine: () => (/* binding */ highlightActiveLine),\n/* harmony export */   highlightActiveLineGutter: () => (/* binding */ highlightActiveLineGutter),\n/* harmony export */   highlightSpecialChars: () => (/* binding */ highlightSpecialChars),\n/* harmony export */   highlightTrailingWhitespace: () => (/* binding */ highlightTrailingWhitespace),\n/* harmony export */   highlightWhitespace: () => (/* binding */ highlightWhitespace),\n/* harmony export */   hoverTooltip: () => (/* binding */ hoverTooltip),\n/* harmony export */   keymap: () => (/* binding */ keymap),\n/* harmony export */   layer: () => (/* binding */ layer),\n/* harmony export */   lineNumberMarkers: () => (/* binding */ lineNumberMarkers),\n/* harmony export */   lineNumbers: () => (/* binding */ lineNumbers),\n/* harmony export */   logException: () => (/* binding */ logException),\n/* harmony export */   panels: () => (/* binding */ panels),\n/* harmony export */   placeholder: () => (/* binding */ placeholder),\n/* harmony export */   rectangularSelection: () => (/* binding */ rectangularSelection),\n/* harmony export */   repositionTooltips: () => (/* binding */ repositionTooltips),\n/* harmony export */   runScopeHandlers: () => (/* binding */ runScopeHandlers),\n/* harmony export */   scrollPastEnd: () => (/* binding */ scrollPastEnd),\n/* harmony export */   showPanel: () => (/* binding */ showPanel),\n/* harmony export */   showTooltip: () => (/* binding */ showTooltip),\n/* harmony export */   tooltips: () => (/* binding */ tooltips)\n/* harmony export */ });\n/* harmony import */ var _codemirror_state__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @codemirror/state */ \"../node_modules/@codemirror/state/dist/index.js\");\n/* harmony import */ var style_mod__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! style-mod */ \"../node_modules/style-mod/src/style-mod.js\");\n/* harmony import */ var w3c_keyname__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! w3c-keyname */ \"../node_modules/w3c-keyname/index.js\");\n\n\n\n\nfunction getSelection(root) {\n    let target;\n    // Browsers differ on whether shadow roots have a getSelection\n    // method. If it exists, use that, otherwise, call it on the\n    // document.\n    if (root.nodeType == 11) { // Shadow root\n        target = root.getSelection ? root : root.ownerDocument;\n    }\n    else {\n        target = root;\n    }\n    return target.getSelection();\n}\nfunction contains(dom, node) {\n    return node ? dom == node || dom.contains(node.nodeType != 1 ? node.parentNode : node) : false;\n}\nfunction deepActiveElement(doc) {\n    let elt = doc.activeElement;\n    while (elt && elt.shadowRoot)\n        elt = elt.shadowRoot.activeElement;\n    return elt;\n}\nfunction hasSelection(dom, selection) {\n    if (!selection.anchorNode)\n        return false;\n    try {\n        // Firefox will raise 'permission denied' errors when accessing\n        // properties of `sel.anchorNode` when it's in a generated CSS\n        // element.\n        return contains(dom, selection.anchorNode);\n    }\n    catch (_) {\n        return false;\n    }\n}\nfunction clientRectsFor(dom) {\n    if (dom.nodeType == 3)\n        return textRange(dom, 0, dom.nodeValue.length).getClientRects();\n    else if (dom.nodeType == 1)\n        return dom.getClientRects();\n    else\n        return [];\n}\n// Scans forward and backward through DOM positions equivalent to the\n// given one to see if the two are in the same place (i.e. after a\n// text node vs at the end of that text node)\nfunction isEquivalentPosition(node, off, targetNode, targetOff) {\n    return targetNode ? (scanFor(node, off, targetNode, targetOff, -1) ||\n        scanFor(node, off, targetNode, targetOff, 1)) : false;\n}\nfunction domIndex(node) {\n    for (var index = 0;; index++) {\n        node = node.previousSibling;\n        if (!node)\n            return index;\n    }\n}\nfunction isBlockElement(node) {\n    return node.nodeType == 1 && /^(DIV|P|LI|UL|OL|BLOCKQUOTE|DD|DT|H\\d|SECTION|PRE)$/.test(node.nodeName);\n}\nfunction scanFor(node, off, targetNode, targetOff, dir) {\n    for (;;) {\n        if (node == targetNode && off == targetOff)\n            return true;\n        if (off == (dir < 0 ? 0 : maxOffset(node))) {\n            if (node.nodeName == \"DIV\")\n                return false;\n            let parent = node.parentNode;\n            if (!parent || parent.nodeType != 1)\n                return false;\n            off = domIndex(node) + (dir < 0 ? 0 : 1);\n            node = parent;\n        }\n        else if (node.nodeType == 1) {\n            node = node.childNodes[off + (dir < 0 ? -1 : 0)];\n            if (node.nodeType == 1 && node.contentEditable == \"false\")\n                return false;\n            off = dir < 0 ? maxOffset(node) : 0;\n        }\n        else {\n            return false;\n        }\n    }\n}\nfunction maxOffset(node) {\n    return node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length;\n}\nfunction flattenRect(rect, left) {\n    let x = left ? rect.left : rect.right;\n    return { left: x, right: x, top: rect.top, bottom: rect.bottom };\n}\nfunction windowRect(win) {\n    let vp = win.visualViewport;\n    if (vp)\n        return {\n            left: 0, right: vp.width,\n            top: 0, bottom: vp.height\n        };\n    return { left: 0, right: win.innerWidth,\n        top: 0, bottom: win.innerHeight };\n}\nfunction getScale(elt, rect) {\n    let scaleX = rect.width / elt.offsetWidth;\n    let scaleY = rect.height / elt.offsetHeight;\n    if (scaleX > 0.995 && scaleX < 1.005 || !isFinite(scaleX) || Math.abs(rect.width - elt.offsetWidth) < 1)\n        scaleX = 1;\n    if (scaleY > 0.995 && scaleY < 1.005 || !isFinite(scaleY) || Math.abs(rect.height - elt.offsetHeight) < 1)\n        scaleY = 1;\n    return { scaleX, scaleY };\n}\nfunction scrollRectIntoView(dom, rect, side, x, y, xMargin, yMargin, ltr) {\n    let doc = dom.ownerDocument, win = doc.defaultView || window;\n    for (let cur = dom, stop = false; cur && !stop;) {\n        if (cur.nodeType == 1) { // Element\n            let bounding, top = cur == doc.body;\n            let scaleX = 1, scaleY = 1;\n            if (top) {\n                bounding = windowRect(win);\n            }\n            else {\n                if (/^(fixed|sticky)$/.test(getComputedStyle(cur).position))\n                    stop = true;\n                if (cur.scrollHeight <= cur.clientHeight && cur.scrollWidth <= cur.clientWidth) {\n                    cur = cur.assignedSlot || cur.parentNode;\n                    continue;\n                }\n                let rect = cur.getBoundingClientRect();\n                ({ scaleX, scaleY } = getScale(cur, rect));\n                // Make sure scrollbar width isn't included in the rectangle\n                bounding = { left: rect.left, right: rect.left + cur.clientWidth * scaleX,\n                    top: rect.top, bottom: rect.top + cur.clientHeight * scaleY };\n            }\n            let moveX = 0, moveY = 0;\n            if (y == \"nearest\") {\n                if (rect.top < bounding.top) {\n                    moveY = -(bounding.top - rect.top + yMargin);\n                    if (side > 0 && rect.bottom > bounding.bottom + moveY)\n                        moveY = rect.bottom - bounding.bottom + moveY + yMargin;\n                }\n                else if (rect.bottom > bounding.bottom) {\n                    moveY = rect.bottom - bounding.bottom + yMargin;\n                    if (side < 0 && (rect.top - moveY) < bounding.top)\n                        moveY = -(bounding.top + moveY - rect.top + yMargin);\n                }\n            }\n            else {\n                let rectHeight = rect.bottom - rect.top, boundingHeight = bounding.bottom - bounding.top;\n                let targetTop = y == \"center\" && rectHeight <= boundingHeight ? rect.top + rectHeight / 2 - boundingHeight / 2 :\n                    y == \"start\" || y == \"center\" && side < 0 ? rect.top - yMargin :\n                        rect.bottom - boundingHeight + yMargin;\n                moveY = targetTop - bounding.top;\n            }\n            if (x == \"nearest\") {\n                if (rect.left < bounding.left) {\n                    moveX = -(bounding.left - rect.left + xMargin);\n                    if (side > 0 && rect.right > bounding.right + moveX)\n                        moveX = rect.right - bounding.right + moveX + xMargin;\n                }\n                else if (rect.right > bounding.right) {\n                    moveX = rect.right - bounding.right + xMargin;\n                    if (side < 0 && rect.left < bounding.left + moveX)\n                        moveX = -(bounding.left + moveX - rect.left + xMargin);\n                }\n            }\n            else {\n                let targetLeft = x == \"center\" ? rect.left + (rect.right - rect.left) / 2 - (bounding.right - bounding.left) / 2 :\n                    (x == \"start\") == ltr ? rect.left - xMargin :\n                        rect.right - (bounding.right - bounding.left) + xMargin;\n                moveX = targetLeft - bounding.left;\n            }\n            if (moveX || moveY) {\n                if (top) {\n                    win.scrollBy(moveX, moveY);\n                }\n                else {\n                    let movedX = 0, movedY = 0;\n                    if (moveY) {\n                        let start = cur.scrollTop;\n                        cur.scrollTop += moveY / scaleY;\n                        movedY = (cur.scrollTop - start) * scaleY;\n                    }\n                    if (moveX) {\n                        let start = cur.scrollLeft;\n                        cur.scrollLeft += moveX / scaleX;\n                        movedX = (cur.scrollLeft - start) * scaleX;\n                    }\n                    rect = { left: rect.left - movedX, top: rect.top - movedY,\n                        right: rect.right - movedX, bottom: rect.bottom - movedY };\n                    if (movedX && Math.abs(movedX - moveX) < 1)\n                        x = \"nearest\";\n                    if (movedY && Math.abs(movedY - moveY) < 1)\n                        y = \"nearest\";\n                }\n            }\n            if (top)\n                break;\n            cur = cur.assignedSlot || cur.parentNode;\n        }\n        else if (cur.nodeType == 11) { // A shadow root\n            cur = cur.host;\n        }\n        else {\n            break;\n        }\n    }\n}\nfunction scrollableParent(dom) {\n    let doc = dom.ownerDocument;\n    for (let cur = dom.parentNode; cur;) {\n        if (cur == doc.body) {\n            break;\n        }\n        else if (cur.nodeType == 1) {\n            if (cur.scrollHeight > cur.clientHeight || cur.scrollWidth > cur.clientWidth)\n                return cur;\n            cur = cur.assignedSlot || cur.parentNode;\n        }\n        else if (cur.nodeType == 11) {\n            cur = cur.host;\n        }\n        else {\n            break;\n        }\n    }\n    return null;\n}\nclass DOMSelectionState {\n    constructor() {\n        this.anchorNode = null;\n        this.anchorOffset = 0;\n        this.focusNode = null;\n        this.focusOffset = 0;\n    }\n    eq(domSel) {\n        return this.anchorNode == domSel.anchorNode && this.anchorOffset == domSel.anchorOffset &&\n            this.focusNode == domSel.focusNode && this.focusOffset == domSel.focusOffset;\n    }\n    setRange(range) {\n        let { anchorNode, focusNode } = range;\n        // Clip offsets to node size to avoid crashes when Safari reports bogus offsets (#1152)\n        this.set(anchorNode, Math.min(range.anchorOffset, anchorNode ? maxOffset(anchorNode) : 0), focusNode, Math.min(range.focusOffset, focusNode ? maxOffset(focusNode) : 0));\n    }\n    set(anchorNode, anchorOffset, focusNode, focusOffset) {\n        this.anchorNode = anchorNode;\n        this.anchorOffset = anchorOffset;\n        this.focusNode = focusNode;\n        this.focusOffset = focusOffset;\n    }\n}\nlet preventScrollSupported = null;\n// Feature-detects support for .focus({preventScroll: true}), and uses\n// a fallback kludge when not supported.\nfunction focusPreventScroll(dom) {\n    if (dom.setActive)\n        return dom.setActive(); // in IE\n    if (preventScrollSupported)\n        return dom.focus(preventScrollSupported);\n    let stack = [];\n    for (let cur = dom; cur; cur = cur.parentNode) {\n        stack.push(cur, cur.scrollTop, cur.scrollLeft);\n        if (cur == cur.ownerDocument)\n            break;\n    }\n    dom.focus(preventScrollSupported == null ? {\n        get preventScroll() {\n            preventScrollSupported = { preventScroll: true };\n            return true;\n        }\n    } : undefined);\n    if (!preventScrollSupported) {\n        preventScrollSupported = false;\n        for (let i = 0; i < stack.length;) {\n            let elt = stack[i++], top = stack[i++], left = stack[i++];\n            if (elt.scrollTop != top)\n                elt.scrollTop = top;\n            if (elt.scrollLeft != left)\n                elt.scrollLeft = left;\n        }\n    }\n}\nlet scratchRange;\nfunction textRange(node, from, to = from) {\n    let range = scratchRange || (scratchRange = document.createRange());\n    range.setEnd(node, to);\n    range.setStart(node, from);\n    return range;\n}\nfunction dispatchKey(elt, name, code, mods) {\n    let options = { key: name, code: name, keyCode: code, which: code, cancelable: true };\n    if (mods)\n        ({ altKey: options.altKey, ctrlKey: options.ctrlKey, shiftKey: options.shiftKey, metaKey: options.metaKey } = mods);\n    let down = new KeyboardEvent(\"keydown\", options);\n    down.synthetic = true;\n    elt.dispatchEvent(down);\n    let up = new KeyboardEvent(\"keyup\", options);\n    up.synthetic = true;\n    elt.dispatchEvent(up);\n    return down.defaultPrevented || up.defaultPrevented;\n}\nfunction getRoot(node) {\n    while (node) {\n        if (node && (node.nodeType == 9 || node.nodeType == 11 && node.host))\n            return node;\n        node = node.assignedSlot || node.parentNode;\n    }\n    return null;\n}\nfunction clearAttributes(node) {\n    while (node.attributes.length)\n        node.removeAttributeNode(node.attributes[0]);\n}\nfunction atElementStart(doc, selection) {\n    let node = selection.focusNode, offset = selection.focusOffset;\n    if (!node || selection.anchorNode != node || selection.anchorOffset != offset)\n        return false;\n    // Safari can report bogus offsets (#1152)\n    offset = Math.min(offset, maxOffset(node));\n    for (;;) {\n        if (offset) {\n            if (node.nodeType != 1)\n                return false;\n            let prev = node.childNodes[offset - 1];\n            if (prev.contentEditable == \"false\")\n                offset--;\n            else {\n                node = prev;\n                offset = maxOffset(node);\n            }\n        }\n        else if (node == doc) {\n            return true;\n        }\n        else {\n            offset = domIndex(node);\n            node = node.parentNode;\n        }\n    }\n}\nfunction isScrolledToBottom(elt) {\n    return elt.scrollTop > Math.max(1, elt.scrollHeight - elt.clientHeight - 4);\n}\nfunction textNodeBefore(startNode, startOffset) {\n    for (let node = startNode, offset = startOffset;;) {\n        if (node.nodeType == 3 && offset > 0) {\n            return { node: node, offset: offset };\n        }\n        else if (node.nodeType == 1 && offset > 0) {\n            if (node.contentEditable == \"false\")\n                return null;\n            node = node.childNodes[offset - 1];\n            offset = maxOffset(node);\n        }\n        else if (node.parentNode && !isBlockElement(node)) {\n            offset = domIndex(node);\n            node = node.parentNode;\n        }\n        else {\n            return null;\n        }\n    }\n}\nfunction textNodeAfter(startNode, startOffset) {\n    for (let node = startNode, offset = startOffset;;) {\n        if (node.nodeType == 3 && offset < node.nodeValue.length) {\n            return { node: node, offset: offset };\n        }\n        else if (node.nodeType == 1 && offset < node.childNodes.length) {\n            if (node.contentEditable == \"false\")\n                return null;\n            node = node.childNodes[offset];\n            offset = 0;\n        }\n        else if (node.parentNode && !isBlockElement(node)) {\n            offset = domIndex(node) + 1;\n            node = node.parentNode;\n        }\n        else {\n            return null;\n        }\n    }\n}\n\nclass DOMPos {\n    constructor(node, offset, precise = true) {\n        this.node = node;\n        this.offset = offset;\n        this.precise = precise;\n    }\n    static before(dom, precise) { return new DOMPos(dom.parentNode, domIndex(dom), precise); }\n    static after(dom, precise) { return new DOMPos(dom.parentNode, domIndex(dom) + 1, precise); }\n}\nconst noChildren = [];\nclass ContentView {\n    constructor() {\n        this.parent = null;\n        this.dom = null;\n        this.flags = 2 /* ViewFlag.NodeDirty */;\n    }\n    get overrideDOMText() { return null; }\n    get posAtStart() {\n        return this.parent ? this.parent.posBefore(this) : 0;\n    }\n    get posAtEnd() {\n        return this.posAtStart + this.length;\n    }\n    posBefore(view) {\n        let pos = this.posAtStart;\n        for (let child of this.children) {\n            if (child == view)\n                return pos;\n            pos += child.length + child.breakAfter;\n        }\n        throw new RangeError(\"Invalid child in posBefore\");\n    }\n    posAfter(view) {\n        return this.posBefore(view) + view.length;\n    }\n    sync(view, track) {\n        if (this.flags & 2 /* ViewFlag.NodeDirty */) {\n            let parent = this.dom;\n            let prev = null, next;\n            for (let child of this.children) {\n                if (child.flags & 7 /* ViewFlag.Dirty */) {\n                    if (!child.dom && (next = prev ? prev.nextSibling : parent.firstChild)) {\n                        let contentView = ContentView.get(next);\n                        if (!contentView || !contentView.parent && contentView.canReuseDOM(child))\n                            child.reuseDOM(next);\n                    }\n                    child.sync(view, track);\n                    child.flags &= ~7 /* ViewFlag.Dirty */;\n                }\n                next = prev ? prev.nextSibling : parent.firstChild;\n                if (track && !track.written && track.node == parent && next != child.dom)\n                    track.written = true;\n                if (child.dom.parentNode == parent) {\n                    while (next && next != child.dom)\n                        next = rm$1(next);\n                }\n                else {\n                    parent.insertBefore(child.dom, next);\n                }\n                prev = child.dom;\n            }\n            next = prev ? prev.nextSibling : parent.firstChild;\n            if (next && track && track.node == parent)\n                track.written = true;\n            while (next)\n                next = rm$1(next);\n        }\n        else if (this.flags & 1 /* ViewFlag.ChildDirty */) {\n            for (let child of this.children)\n                if (child.flags & 7 /* ViewFlag.Dirty */) {\n                    child.sync(view, track);\n                    child.flags &= ~7 /* ViewFlag.Dirty */;\n                }\n        }\n    }\n    reuseDOM(_dom) { }\n    localPosFromDOM(node, offset) {\n        let after;\n        if (node == this.dom) {\n            after = this.dom.childNodes[offset];\n        }\n        else {\n            let bias = maxOffset(node) == 0 ? 0 : offset == 0 ? -1 : 1;\n            for (;;) {\n                let parent = node.parentNode;\n                if (parent == this.dom)\n                    break;\n                if (bias == 0 && parent.firstChild != parent.lastChild) {\n                    if (node == parent.firstChild)\n                        bias = -1;\n                    else\n                        bias = 1;\n                }\n                node = parent;\n            }\n            if (bias < 0)\n                after = node;\n            else\n                after = node.nextSibling;\n        }\n        if (after == this.dom.firstChild)\n            return 0;\n        while (after && !ContentView.get(after))\n            after = after.nextSibling;\n        if (!after)\n            return this.length;\n        for (let i = 0, pos = 0;; i++) {\n            let child = this.children[i];\n            if (child.dom == after)\n                return pos;\n            pos += child.length + child.breakAfter;\n        }\n    }\n    domBoundsAround(from, to, offset = 0) {\n        let fromI = -1, fromStart = -1, toI = -1, toEnd = -1;\n        for (let i = 0, pos = offset, prevEnd = offset; i < this.children.length; i++) {\n            let child = this.children[i], end = pos + child.length;\n            if (pos < from && end > to)\n                return child.domBoundsAround(from, to, pos);\n            if (end >= from && fromI == -1) {\n                fromI = i;\n                fromStart = pos;\n            }\n            if (pos > to && child.dom.parentNode == this.dom) {\n                toI = i;\n                toEnd = prevEnd;\n                break;\n            }\n            prevEnd = end;\n            pos = end + child.breakAfter;\n        }\n        return { from: fromStart, to: toEnd < 0 ? offset + this.length : toEnd,\n            startDOM: (fromI ? this.children[fromI - 1].dom.nextSibling : null) || this.dom.firstChild,\n            endDOM: toI < this.children.length && toI >= 0 ? this.children[toI].dom : null };\n    }\n    markDirty(andParent = false) {\n        this.flags |= 2 /* ViewFlag.NodeDirty */;\n        this.markParentsDirty(andParent);\n    }\n    markParentsDirty(childList) {\n        for (let parent = this.parent; parent; parent = parent.parent) {\n            if (childList)\n                parent.flags |= 2 /* ViewFlag.NodeDirty */;\n            if (parent.flags & 1 /* ViewFlag.ChildDirty */)\n                return;\n            parent.flags |= 1 /* ViewFlag.ChildDirty */;\n            childList = false;\n        }\n    }\n    setParent(parent) {\n        if (this.parent != parent) {\n            this.parent = parent;\n            if (this.flags & 7 /* ViewFlag.Dirty */)\n                this.markParentsDirty(true);\n        }\n    }\n    setDOM(dom) {\n        if (this.dom == dom)\n            return;\n        if (this.dom)\n            this.dom.cmView = null;\n        this.dom = dom;\n        dom.cmView = this;\n    }\n    get rootView() {\n        for (let v = this;;) {\n            let parent = v.parent;\n            if (!parent)\n                return v;\n            v = parent;\n        }\n    }\n    replaceChildren(from, to, children = noChildren) {\n        this.markDirty();\n        for (let i = from; i < to; i++) {\n            let child = this.children[i];\n            if (child.parent == this && children.indexOf(child) < 0)\n                child.destroy();\n        }\n        this.children.splice(from, to - from, ...children);\n        for (let i = 0; i < children.length; i++)\n            children[i].setParent(this);\n    }\n    ignoreMutation(_rec) { return false; }\n    ignoreEvent(_event) { return false; }\n    childCursor(pos = this.length) {\n        return new ChildCursor(this.children, pos, this.children.length);\n    }\n    childPos(pos, bias = 1) {\n        return this.childCursor().findPos(pos, bias);\n    }\n    toString() {\n        let name = this.constructor.name.replace(\"View\", \"\");\n        return name + (this.children.length ? \"(\" + this.children.join() + \")\" :\n            this.length ? \"[\" + (name == \"Text\" ? this.text : this.length) + \"]\" : \"\") +\n            (this.breakAfter ? \"#\" : \"\");\n    }\n    static get(node) { return node.cmView; }\n    get isEditable() { return true; }\n    get isWidget() { return false; }\n    get isHidden() { return false; }\n    merge(from, to, source, hasStart, openStart, openEnd) {\n        return false;\n    }\n    become(other) { return false; }\n    canReuseDOM(other) {\n        return other.constructor == this.constructor && !((this.flags | other.flags) & 8 /* ViewFlag.Composition */);\n    }\n    // When this is a zero-length view with a side, this should return a\n    // number <= 0 to indicate it is before its position, or a\n    // number > 0 when after its position.\n    getSide() { return 0; }\n    destroy() {\n        for (let child of this.children)\n            if (child.parent == this)\n                child.destroy();\n        this.parent = null;\n    }\n}\nContentView.prototype.breakAfter = 0;\n// Remove a DOM node and return its next sibling.\nfunction rm$1(dom) {\n    let next = dom.nextSibling;\n    dom.parentNode.removeChild(dom);\n    return next;\n}\nclass ChildCursor {\n    constructor(children, pos, i) {\n        this.children = children;\n        this.pos = pos;\n        this.i = i;\n        this.off = 0;\n    }\n    findPos(pos, bias = 1) {\n        for (;;) {\n            if (pos > this.pos || pos == this.pos &&\n                (bias > 0 || this.i == 0 || this.children[this.i - 1].breakAfter)) {\n                this.off = pos - this.pos;\n                return this;\n            }\n            let next = this.children[--this.i];\n            this.pos -= next.length + next.breakAfter;\n        }\n    }\n}\nfunction replaceRange(parent, fromI, fromOff, toI, toOff, insert, breakAtStart, openStart, openEnd) {\n    let { children } = parent;\n    let before = children.length ? children[fromI] : null;\n    let last = insert.length ? insert[insert.length - 1] : null;\n    let breakAtEnd = last ? last.breakAfter : breakAtStart;\n    // Change within a single child\n    if (fromI == toI && before && !breakAtStart && !breakAtEnd && insert.length < 2 &&\n        before.merge(fromOff, toOff, insert.length ? last : null, fromOff == 0, openStart, openEnd))\n        return;\n    if (toI < children.length) {\n        let after = children[toI];\n        // Make sure the end of the child after the update is preserved in `after`\n        if (after && (toOff < after.length || after.breakAfter && (last === null || last === void 0 ? void 0 : last.breakAfter))) {\n            // If we're splitting a child, separate part of it to avoid that\n            // being mangled when updating the child before the update.\n            if (fromI == toI) {\n                after = after.split(toOff);\n                toOff = 0;\n            }\n            // If the element after the replacement should be merged with\n            // the last replacing element, update `content`\n            if (!breakAtEnd && last && after.merge(0, toOff, last, true, 0, openEnd)) {\n                insert[insert.length - 1] = after;\n            }\n            else {\n                // Remove the start of the after element, if necessary, and\n                // add it to `content`.\n                if (toOff || after.children.length && !after.children[0].length)\n                    after.merge(0, toOff, null, false, 0, openEnd);\n                insert.push(after);\n            }\n        }\n        else if (after === null || after === void 0 ? void 0 : after.breakAfter) {\n            // The element at `toI` is entirely covered by this range.\n            // Preserve its line break, if any.\n            if (last)\n                last.breakAfter = 1;\n            else\n                breakAtStart = 1;\n        }\n        // Since we've handled the next element from the current elements\n        // now, make sure `toI` points after that.\n        toI++;\n    }\n    if (before) {\n        before.breakAfter = breakAtStart;\n        if (fromOff > 0) {\n            if (!breakAtStart && insert.length && before.merge(fromOff, before.length, insert[0], false, openStart, 0)) {\n                before.breakAfter = insert.shift().breakAfter;\n            }\n            else if (fromOff < before.length || before.children.length && before.children[before.children.length - 1].length == 0) {\n                before.merge(fromOff, before.length, null, false, openStart, 0);\n            }\n            fromI++;\n        }\n    }\n    // Try to merge widgets on the boundaries of the replacement\n    while (fromI < toI && insert.length) {\n        if (children[toI - 1].become(insert[insert.length - 1])) {\n            toI--;\n            insert.pop();\n            openEnd = insert.length ? 0 : openStart;\n        }\n        else if (children[fromI].become(insert[0])) {\n            fromI++;\n            insert.shift();\n            openStart = insert.length ? 0 : openEnd;\n        }\n        else {\n            break;\n        }\n    }\n    if (!insert.length && fromI && toI < children.length && !children[fromI - 1].breakAfter &&\n        children[toI].merge(0, 0, children[fromI - 1], false, openStart, openEnd))\n        fromI--;\n    if (fromI < toI || insert.length)\n        parent.replaceChildren(fromI, toI, insert);\n}\nfunction mergeChildrenInto(parent, from, to, insert, openStart, openEnd) {\n    let cur = parent.childCursor();\n    let { i: toI, off: toOff } = cur.findPos(to, 1);\n    let { i: fromI, off: fromOff } = cur.findPos(from, -1);\n    let dLen = from - to;\n    for (let view of insert)\n        dLen += view.length;\n    parent.length += dLen;\n    replaceRange(parent, fromI, fromOff, toI, toOff, insert, 0, openStart, openEnd);\n}\n\nlet nav = typeof navigator != \"undefined\" ? navigator : { userAgent: \"\", vendor: \"\", platform: \"\" };\nlet doc = typeof document != \"undefined\" ? document : { documentElement: { style: {} } };\nconst ie_edge = /*@__PURE__*//Edge\\/(\\d+)/.exec(nav.userAgent);\nconst ie_upto10 = /*@__PURE__*//MSIE \\d/.test(nav.userAgent);\nconst ie_11up = /*@__PURE__*//Trident\\/(?:[7-9]|\\d{2,})\\..*rv:(\\d+)/.exec(nav.userAgent);\nconst ie = !!(ie_upto10 || ie_11up || ie_edge);\nconst gecko = !ie && /*@__PURE__*//gecko\\/(\\d+)/i.test(nav.userAgent);\nconst chrome = !ie && /*@__PURE__*//Chrome\\/(\\d+)/.exec(nav.userAgent);\nconst webkit = \"webkitFontSmoothing\" in doc.documentElement.style;\nconst safari = !ie && /*@__PURE__*//Apple Computer/.test(nav.vendor);\nconst ios = safari && (/*@__PURE__*//Mobile\\/\\w+/.test(nav.userAgent) || nav.maxTouchPoints > 2);\nvar browser = {\n    mac: ios || /*@__PURE__*//Mac/.test(nav.platform),\n    windows: /*@__PURE__*//Win/.test(nav.platform),\n    linux: /*@__PURE__*//Linux|X11/.test(nav.platform),\n    ie,\n    ie_version: ie_upto10 ? doc.documentMode || 6 : ie_11up ? +ie_11up[1] : ie_edge ? +ie_edge[1] : 0,\n    gecko,\n    gecko_version: gecko ? +(/*@__PURE__*//Firefox\\/(\\d+)/.exec(nav.userAgent) || [0, 0])[1] : 0,\n    chrome: !!chrome,\n    chrome_version: chrome ? +chrome[1] : 0,\n    ios,\n    android: /*@__PURE__*//Android\\b/.test(nav.userAgent),\n    webkit,\n    safari,\n    webkit_version: webkit ? +(/*@__PURE__*//\\bAppleWebKit\\/(\\d+)/.exec(nav.userAgent) || [0, 0])[1] : 0,\n    tabSize: doc.documentElement.style.tabSize != null ? \"tab-size\" : \"-moz-tab-size\"\n};\n\nconst MaxJoinLen = 256;\nclass TextView extends ContentView {\n    constructor(text) {\n        super();\n        this.text = text;\n    }\n    get length() { return this.text.length; }\n    createDOM(textDOM) {\n        this.setDOM(textDOM || document.createTextNode(this.text));\n    }\n    sync(view, track) {\n        if (!this.dom)\n            this.createDOM();\n        if (this.dom.nodeValue != this.text) {\n            if (track && track.node == this.dom)\n                track.written = true;\n            this.dom.nodeValue = this.text;\n        }\n    }\n    reuseDOM(dom) {\n        if (dom.nodeType == 3)\n            this.createDOM(dom);\n    }\n    merge(from, to, source) {\n        if ((this.flags & 8 /* ViewFlag.Composition */) ||\n            source && (!(source instanceof TextView) ||\n                this.length - (to - from) + source.length > MaxJoinLen ||\n                (source.flags & 8 /* ViewFlag.Composition */)))\n            return false;\n        this.text = this.text.slice(0, from) + (source ? source.text : \"\") + this.text.slice(to);\n        this.markDirty();\n        return true;\n    }\n    split(from) {\n        let result = new TextView(this.text.slice(from));\n        this.text = this.text.slice(0, from);\n        this.markDirty();\n        result.flags |= this.flags & 8 /* ViewFlag.Composition */;\n        return result;\n    }\n    localPosFromDOM(node, offset) {\n        return node == this.dom ? offset : offset ? this.text.length : 0;\n    }\n    domAtPos(pos) { return new DOMPos(this.dom, pos); }\n    domBoundsAround(_from, _to, offset) {\n        return { from: offset, to: offset + this.length, startDOM: this.dom, endDOM: this.dom.nextSibling };\n    }\n    coordsAt(pos, side) {\n        return textCoords(this.dom, pos, side);\n    }\n}\nclass MarkView extends ContentView {\n    constructor(mark, children = [], length = 0) {\n        super();\n        this.mark = mark;\n        this.children = children;\n        this.length = length;\n        for (let ch of children)\n            ch.setParent(this);\n    }\n    setAttrs(dom) {\n        clearAttributes(dom);\n        if (this.mark.class)\n            dom.className = this.mark.class;\n        if (this.mark.attrs)\n            for (let name in this.mark.attrs)\n                dom.setAttribute(name, this.mark.attrs[name]);\n        return dom;\n    }\n    canReuseDOM(other) {\n        return super.canReuseDOM(other) && !((this.flags | other.flags) & 8 /* ViewFlag.Composition */);\n    }\n    reuseDOM(node) {\n        if (node.nodeName == this.mark.tagName.toUpperCase()) {\n            this.setDOM(node);\n            this.flags |= 4 /* ViewFlag.AttrsDirty */ | 2 /* ViewFlag.NodeDirty */;\n        }\n    }\n    sync(view, track) {\n        if (!this.dom)\n            this.setDOM(this.setAttrs(document.createElement(this.mark.tagName)));\n        else if (this.flags & 4 /* ViewFlag.AttrsDirty */)\n            this.setAttrs(this.dom);\n        super.sync(view, track);\n    }\n    merge(from, to, source, _hasStart, openStart, openEnd) {\n        if (source && (!(source instanceof MarkView && source.mark.eq(this.mark)) ||\n            (from && openStart <= 0) || (to < this.length && openEnd <= 0)))\n            return false;\n        mergeChildrenInto(this, from, to, source ? source.children.slice() : [], openStart - 1, openEnd - 1);\n        this.markDirty();\n        return true;\n    }\n    split(from) {\n        let result = [], off = 0, detachFrom = -1, i = 0;\n        for (let elt of this.children) {\n            let end = off + elt.length;\n            if (end > from)\n                result.push(off < from ? elt.split(from - off) : elt);\n            if (detachFrom < 0 && off >= from)\n                detachFrom = i;\n            off = end;\n            i++;\n        }\n        let length = this.length - from;\n        this.length = from;\n        if (detachFrom > -1) {\n            this.children.length = detachFrom;\n            this.markDirty();\n        }\n        return new MarkView(this.mark, result, length);\n    }\n    domAtPos(pos) {\n        return inlineDOMAtPos(this, pos);\n    }\n    coordsAt(pos, side) {\n        return coordsInChildren(this, pos, side);\n    }\n}\nfunction textCoords(text, pos, side) {\n    let length = text.nodeValue.length;\n    if (pos > length)\n        pos = length;\n    let from = pos, to = pos, flatten = 0;\n    if (pos == 0 && side < 0 || pos == length && side >= 0) {\n        if (!(browser.chrome || browser.gecko)) { // These browsers reliably return valid rectangles for empty ranges\n            if (pos) {\n                from--;\n                flatten = 1;\n            } // FIXME this is wrong in RTL text\n            else if (to < length) {\n                to++;\n                flatten = -1;\n            }\n        }\n    }\n    else {\n        if (side < 0)\n            from--;\n        else if (to < length)\n            to++;\n    }\n    let rects = textRange(text, from, to).getClientRects();\n    if (!rects.length)\n        return null;\n    let rect = rects[(flatten ? flatten < 0 : side >= 0) ? 0 : rects.length - 1];\n    if (browser.safari && !flatten && rect.width == 0)\n        rect = Array.prototype.find.call(rects, r => r.width) || rect;\n    return flatten ? flattenRect(rect, flatten < 0) : rect || null;\n}\n// Also used for collapsed ranges that don't have a placeholder widget!\nclass WidgetView extends ContentView {\n    static create(widget, length, side) {\n        return new WidgetView(widget, length, side);\n    }\n    constructor(widget, length, side) {\n        super();\n        this.widget = widget;\n        this.length = length;\n        this.side = side;\n        this.prevWidget = null;\n    }\n    split(from) {\n        let result = WidgetView.create(this.widget, this.length - from, this.side);\n        this.length -= from;\n        return result;\n    }\n    sync(view) {\n        if (!this.dom || !this.widget.updateDOM(this.dom, view)) {\n            if (this.dom && this.prevWidget)\n                this.prevWidget.destroy(this.dom);\n            this.prevWidget = null;\n            this.setDOM(this.widget.toDOM(view));\n            if (!this.widget.editable)\n                this.dom.contentEditable = \"false\";\n        }\n    }\n    getSide() { return this.side; }\n    merge(from, to, source, hasStart, openStart, openEnd) {\n        if (source && (!(source instanceof WidgetView) || !this.widget.compare(source.widget) ||\n            from > 0 && openStart <= 0 || to < this.length && openEnd <= 0))\n            return false;\n        this.length = from + (source ? source.length : 0) + (this.length - to);\n        return true;\n    }\n    become(other) {\n        if (other instanceof WidgetView && other.side == this.side &&\n            this.widget.constructor == other.widget.constructor) {\n            if (!this.widget.compare(other.widget))\n                this.markDirty(true);\n            if (this.dom && !this.prevWidget)\n                this.prevWidget = this.widget;\n            this.widget = other.widget;\n            this.length = other.length;\n            return true;\n        }\n        return false;\n    }\n    ignoreMutation() { return true; }\n    ignoreEvent(event) { return this.widget.ignoreEvent(event); }\n    get overrideDOMText() {\n        if (this.length == 0)\n            return _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.Text.empty;\n        let top = this;\n        while (top.parent)\n            top = top.parent;\n        let { view } = top, text = view && view.state.doc, start = this.posAtStart;\n        return text ? text.slice(start, start + this.length) : _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.Text.empty;\n    }\n    domAtPos(pos) {\n        return (this.length ? pos == 0 : this.side > 0)\n            ? DOMPos.before(this.dom)\n            : DOMPos.after(this.dom, pos == this.length);\n    }\n    domBoundsAround() { return null; }\n    coordsAt(pos, side) {\n        let custom = this.widget.coordsAt(this.dom, pos, side);\n        if (custom)\n            return custom;\n        let rects = this.dom.getClientRects(), rect = null;\n        if (!rects.length)\n            return null;\n        let fromBack = this.side ? this.side < 0 : pos > 0;\n        for (let i = fromBack ? rects.length - 1 : 0;; i += (fromBack ? -1 : 1)) {\n            rect = rects[i];\n            if (pos > 0 ? i == 0 : i == rects.length - 1 || rect.top < rect.bottom)\n                break;\n        }\n        return flattenRect(rect, !fromBack);\n    }\n    get isEditable() { return false; }\n    get isWidget() { return true; }\n    get isHidden() { return this.widget.isHidden; }\n    destroy() {\n        super.destroy();\n        if (this.dom)\n            this.widget.destroy(this.dom);\n    }\n}\n// These are drawn around uneditable widgets to avoid a number of\n// browser bugs that show up when the cursor is directly next to\n// uneditable inline content.\nclass WidgetBufferView extends ContentView {\n    constructor(side) {\n        super();\n        this.side = side;\n    }\n    get length() { return 0; }\n    merge() { return false; }\n    become(other) {\n        return other instanceof WidgetBufferView && other.side == this.side;\n    }\n    split() { return new WidgetBufferView(this.side); }\n    sync() {\n        if (!this.dom) {\n            let dom = document.createElement(\"img\");\n            dom.className = \"cm-widgetBuffer\";\n            dom.setAttribute(\"aria-hidden\", \"true\");\n            this.setDOM(dom);\n        }\n    }\n    getSide() { return this.side; }\n    domAtPos(pos) { return this.side > 0 ? DOMPos.before(this.dom) : DOMPos.after(this.dom); }\n    localPosFromDOM() { return 0; }\n    domBoundsAround() { return null; }\n    coordsAt(pos) {\n        return this.dom.getBoundingClientRect();\n    }\n    get overrideDOMText() {\n        return _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.Text.empty;\n    }\n    get isHidden() { return true; }\n}\nTextView.prototype.children = WidgetView.prototype.children = WidgetBufferView.prototype.children = noChildren;\nfunction inlineDOMAtPos(parent, pos) {\n    let dom = parent.dom, { children } = parent, i = 0;\n    for (let off = 0; i < children.length; i++) {\n        let child = children[i], end = off + child.length;\n        if (end == off && child.getSide() <= 0)\n            continue;\n        if (pos > off && pos < end && child.dom.parentNode == dom)\n            return child.domAtPos(pos - off);\n        if (pos <= off)\n            break;\n        off = end;\n    }\n    for (let j = i; j > 0; j--) {\n        let prev = children[j - 1];\n        if (prev.dom.parentNode == dom)\n            return prev.domAtPos(prev.length);\n    }\n    for (let j = i; j < children.length; j++) {\n        let next = children[j];\n        if (next.dom.parentNode == dom)\n            return next.domAtPos(0);\n    }\n    return new DOMPos(dom, 0);\n}\n// Assumes `view`, if a mark view, has precisely 1 child.\nfunction joinInlineInto(parent, view, open) {\n    let last, { children } = parent;\n    if (open > 0 && view instanceof MarkView && children.length &&\n        (last = children[children.length - 1]) instanceof MarkView && last.mark.eq(view.mark)) {\n        joinInlineInto(last, view.children[0], open - 1);\n    }\n    else {\n        children.push(view);\n        view.setParent(parent);\n    }\n    parent.length += view.length;\n}\nfunction coordsInChildren(view, pos, side) {\n    let before = null, beforePos = -1, after = null, afterPos = -1;\n    function scan(view, pos) {\n        for (let i = 0, off = 0; i < view.children.length && off <= pos; i++) {\n            let child = view.children[i], end = off + child.length;\n            if (end >= pos) {\n                if (child.children.length) {\n                    scan(child, pos - off);\n                }\n                else if ((!after || after.isHidden && side > 0) &&\n                    (end > pos || off == end && child.getSide() > 0)) {\n                    after = child;\n                    afterPos = pos - off;\n                }\n                else if (off < pos || (off == end && child.getSide() < 0) && !child.isHidden) {\n                    before = child;\n                    beforePos = pos - off;\n                }\n            }\n            off = end;\n        }\n    }\n    scan(view, pos);\n    let target = (side < 0 ? before : after) || before || after;\n    if (target)\n        return target.coordsAt(Math.max(0, target == before ? beforePos : afterPos), side);\n    return fallbackRect(view);\n}\nfunction fallbackRect(view) {\n    let last = view.dom.lastChild;\n    if (!last)\n        return view.dom.getBoundingClientRect();\n    let rects = clientRectsFor(last);\n    return rects[rects.length - 1] || null;\n}\n\nfunction combineAttrs(source, target) {\n    for (let name in source) {\n        if (name == \"class\" && target.class)\n            target.class += \" \" + source.class;\n        else if (name == \"style\" && target.style)\n            target.style += \";\" + source.style;\n        else\n            target[name] = source[name];\n    }\n    return target;\n}\nconst noAttrs = /*@__PURE__*/Object.create(null);\nfunction attrsEq(a, b, ignore) {\n    if (a == b)\n        return true;\n    if (!a)\n        a = noAttrs;\n    if (!b)\n        b = noAttrs;\n    let keysA = Object.keys(a), keysB = Object.keys(b);\n    if (keysA.length - (ignore && keysA.indexOf(ignore) > -1 ? 1 : 0) !=\n        keysB.length - (ignore && keysB.indexOf(ignore) > -1 ? 1 : 0))\n        return false;\n    for (let key of keysA) {\n        if (key != ignore && (keysB.indexOf(key) == -1 || a[key] !== b[key]))\n            return false;\n    }\n    return true;\n}\nfunction updateAttrs(dom, prev, attrs) {\n    let changed = false;\n    if (prev)\n        for (let name in prev)\n            if (!(attrs && name in attrs)) {\n                changed = true;\n                if (name == \"style\")\n                    dom.style.cssText = \"\";\n                else\n                    dom.removeAttribute(name);\n            }\n    if (attrs)\n        for (let name in attrs)\n            if (!(prev && prev[name] == attrs[name])) {\n                changed = true;\n                if (name == \"style\")\n                    dom.style.cssText = attrs[name];\n                else\n                    dom.setAttribute(name, attrs[name]);\n            }\n    return changed;\n}\nfunction getAttrs(dom) {\n    let attrs = Object.create(null);\n    for (let i = 0; i < dom.attributes.length; i++) {\n        let attr = dom.attributes[i];\n        attrs[attr.name] = attr.value;\n    }\n    return attrs;\n}\n\nclass LineView extends ContentView {\n    constructor() {\n        super(...arguments);\n        this.children = [];\n        this.length = 0;\n        this.prevAttrs = undefined;\n        this.attrs = null;\n        this.breakAfter = 0;\n    }\n    // Consumes source\n    merge(from, to, source, hasStart, openStart, openEnd) {\n        if (source) {\n            if (!(source instanceof LineView))\n                return false;\n            if (!this.dom)\n                source.transferDOM(this); // Reuse source.dom when appropriate\n        }\n        if (hasStart)\n            this.setDeco(source ? source.attrs : null);\n        mergeChildrenInto(this, from, to, source ? source.children.slice() : [], openStart, openEnd);\n        return true;\n    }\n    split(at) {\n        let end = new LineView;\n        end.breakAfter = this.breakAfter;\n        if (this.length == 0)\n            return end;\n        let { i, off } = this.childPos(at);\n        if (off) {\n            end.append(this.children[i].split(off), 0);\n            this.children[i].merge(off, this.children[i].length, null, false, 0, 0);\n            i++;\n        }\n        for (let j = i; j < this.children.length; j++)\n            end.append(this.children[j], 0);\n        while (i > 0 && this.children[i - 1].length == 0)\n            this.children[--i].destroy();\n        this.children.length = i;\n        this.markDirty();\n        this.length = at;\n        return end;\n    }\n    transferDOM(other) {\n        if (!this.dom)\n            return;\n        this.markDirty();\n        other.setDOM(this.dom);\n        other.prevAttrs = this.prevAttrs === undefined ? this.attrs : this.prevAttrs;\n        this.prevAttrs = undefined;\n        this.dom = null;\n    }\n    setDeco(attrs) {\n        if (!attrsEq(this.attrs, attrs)) {\n            if (this.dom) {\n                this.prevAttrs = this.attrs;\n                this.markDirty();\n            }\n            this.attrs = attrs;\n        }\n    }\n    append(child, openStart) {\n        joinInlineInto(this, child, openStart);\n    }\n    // Only called when building a line view in ContentBuilder\n    addLineDeco(deco) {\n        let attrs = deco.spec.attributes, cls = deco.spec.class;\n        if (attrs)\n            this.attrs = combineAttrs(attrs, this.attrs || {});\n        if (cls)\n            this.attrs = combineAttrs({ class: cls }, this.attrs || {});\n    }\n    domAtPos(pos) {\n        return inlineDOMAtPos(this, pos);\n    }\n    reuseDOM(node) {\n        if (node.nodeName == \"DIV\") {\n            this.setDOM(node);\n            this.flags |= 4 /* ViewFlag.AttrsDirty */ | 2 /* ViewFlag.NodeDirty */;\n        }\n    }\n    sync(view, track) {\n        var _a;\n        if (!this.dom) {\n            this.setDOM(document.createElement(\"div\"));\n            this.dom.className = \"cm-line\";\n            this.prevAttrs = this.attrs ? null : undefined;\n        }\n        else if (this.flags & 4 /* ViewFlag.AttrsDirty */) {\n            clearAttributes(this.dom);\n            this.dom.className = \"cm-line\";\n            this.prevAttrs = this.attrs ? null : undefined;\n        }\n        if (this.prevAttrs !== undefined) {\n            updateAttrs(this.dom, this.prevAttrs, this.attrs);\n            this.dom.classList.add(\"cm-line\");\n            this.prevAttrs = undefined;\n        }\n        super.sync(view, track);\n        let last = this.dom.lastChild;\n        while (last && ContentView.get(last) instanceof MarkView)\n            last = last.lastChild;\n        if (!last || !this.length ||\n            last.nodeName != \"BR\" && ((_a = ContentView.get(last)) === null || _a === void 0 ? void 0 : _a.isEditable) == false &&\n                (!browser.ios || !this.children.some(ch => ch instanceof TextView))) {\n            let hack = document.createElement(\"BR\");\n            hack.cmIgnore = true;\n            this.dom.appendChild(hack);\n        }\n    }\n    measureTextSize() {\n        if (this.children.length == 0 || this.length > 20)\n            return null;\n        let totalWidth = 0, textHeight;\n        for (let child of this.children) {\n            if (!(child instanceof TextView) || /[^ -~]/.test(child.text))\n                return null;\n            let rects = clientRectsFor(child.dom);\n            if (rects.length != 1)\n                return null;\n            totalWidth += rects[0].width;\n            textHeight = rects[0].height;\n        }\n        return !totalWidth ? null : {\n            lineHeight: this.dom.getBoundingClientRect().height,\n            charWidth: totalWidth / this.length,\n            textHeight\n        };\n    }\n    coordsAt(pos, side) {\n        let rect = coordsInChildren(this, pos, side);\n        // Correct rectangle height for empty lines when the returned\n        // height is larger than the text height.\n        if (!this.children.length && rect && this.parent) {\n            let { heightOracle } = this.parent.view.viewState, height = rect.bottom - rect.top;\n            if (Math.abs(height - heightOracle.lineHeight) < 2 && heightOracle.textHeight < height) {\n                let dist = (height - heightOracle.textHeight) / 2;\n                return { top: rect.top + dist, bottom: rect.bottom - dist, left: rect.left, right: rect.left };\n            }\n        }\n        return rect;\n    }\n    become(other) {\n        return other instanceof LineView && this.children.length == 0 && other.children.length == 0 &&\n            attrsEq(this.attrs, other.attrs) && this.breakAfter == other.breakAfter;\n    }\n    covers() { return true; }\n    static find(docView, pos) {\n        for (let i = 0, off = 0; i < docView.children.length; i++) {\n            let block = docView.children[i], end = off + block.length;\n            if (end >= pos) {\n                if (block instanceof LineView)\n                    return block;\n                if (end > pos)\n                    break;\n            }\n            off = end + block.breakAfter;\n        }\n        return null;\n    }\n}\nclass BlockWidgetView extends ContentView {\n    constructor(widget, length, deco) {\n        super();\n        this.widget = widget;\n        this.length = length;\n        this.deco = deco;\n        this.breakAfter = 0;\n        this.prevWidget = null;\n    }\n    merge(from, to, source, _takeDeco, openStart, openEnd) {\n        if (source && (!(source instanceof BlockWidgetView) || !this.widget.compare(source.widget) ||\n            from > 0 && openStart <= 0 || to < this.length && openEnd <= 0))\n            return false;\n        this.length = from + (source ? source.length : 0) + (this.length - to);\n        return true;\n    }\n    domAtPos(pos) {\n        return pos == 0 ? DOMPos.before(this.dom) : DOMPos.after(this.dom, pos == this.length);\n    }\n    split(at) {\n        let len = this.length - at;\n        this.length = at;\n        let end = new BlockWidgetView(this.widget, len, this.deco);\n        end.breakAfter = this.breakAfter;\n        return end;\n    }\n    get children() { return noChildren; }\n    sync(view) {\n        if (!this.dom || !this.widget.updateDOM(this.dom, view)) {\n            if (this.dom && this.prevWidget)\n                this.prevWidget.destroy(this.dom);\n            this.prevWidget = null;\n            this.setDOM(this.widget.toDOM(view));\n            if (!this.widget.editable)\n                this.dom.contentEditable = \"false\";\n        }\n    }\n    get overrideDOMText() {\n        return this.parent ? this.parent.view.state.doc.slice(this.posAtStart, this.posAtEnd) : _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.Text.empty;\n    }\n    domBoundsAround() { return null; }\n    become(other) {\n        if (other instanceof BlockWidgetView &&\n            other.widget.constructor == this.widget.constructor) {\n            if (!other.widget.compare(this.widget))\n                this.markDirty(true);\n            if (this.dom && !this.prevWidget)\n                this.prevWidget = this.widget;\n            this.widget = other.widget;\n            this.length = other.length;\n            this.deco = other.deco;\n            this.breakAfter = other.breakAfter;\n            return true;\n        }\n        return false;\n    }\n    ignoreMutation() { return true; }\n    ignoreEvent(event) { return this.widget.ignoreEvent(event); }\n    get isEditable() { return false; }\n    get isWidget() { return true; }\n    coordsAt(pos, side) {\n        return this.widget.coordsAt(this.dom, pos, side);\n    }\n    destroy() {\n        super.destroy();\n        if (this.dom)\n            this.widget.destroy(this.dom);\n    }\n    covers(side) {\n        let { startSide, endSide } = this.deco;\n        return startSide == endSide ? false : side < 0 ? startSide < 0 : endSide > 0;\n    }\n}\n\n/**\nWidgets added to the content are described by subclasses of this\nclass. Using a description object like that makes it possible to\ndelay creating of the DOM structure for a widget until it is\nneeded, and to avoid redrawing widgets even if the decorations\nthat define them are recreated.\n*/\nclass WidgetType {\n    /**\n    Compare this instance to another instance of the same type.\n    (TypeScript can't express this, but only instances of the same\n    specific class will be passed to this method.) This is used to\n    avoid redrawing widgets when they are replaced by a new\n    decoration of the same type. The default implementation just\n    returns `false`, which will cause new instances of the widget to\n    always be redrawn.\n    */\n    eq(widget) { return false; }\n    /**\n    Update a DOM element created by a widget of the same type (but\n    different, non-`eq` content) to reflect this widget. May return\n    true to indicate that it could update, false to indicate it\n    couldn't (in which case the widget will be redrawn). The default\n    implementation just returns false.\n    */\n    updateDOM(dom, view) { return false; }\n    /**\n    @internal\n    */\n    compare(other) {\n        return this == other || this.constructor == other.constructor && this.eq(other);\n    }\n    /**\n    The estimated height this widget will have, to be used when\n    estimating the height of content that hasn't been drawn. May\n    return -1 to indicate you don't know. The default implementation\n    returns -1.\n    */\n    get estimatedHeight() { return -1; }\n    /**\n    For inline widgets that are displayed inline (as opposed to\n    `inline-block`) and introduce line breaks (through `<br>` tags\n    or textual newlines), this must indicate the amount of line\n    breaks they introduce. Defaults to 0.\n    */\n    get lineBreaks() { return 0; }\n    /**\n    Can be used to configure which kinds of events inside the widget\n    should be ignored by the editor. The default is to ignore all\n    events.\n    */\n    ignoreEvent(event) { return true; }\n    /**\n    Override the way screen coordinates for positions at/in the\n    widget are found. `pos` will be the offset into the widget, and\n    `side` the side of the position that is being queried—less than\n    zero for before, greater than zero for after, and zero for\n    directly at that position.\n    */\n    coordsAt(dom, pos, side) { return null; }\n    /**\n    @internal\n    */\n    get isHidden() { return false; }\n    /**\n    @internal\n    */\n    get editable() { return false; }\n    /**\n    This is called when the an instance of the widget is removed\n    from the editor view.\n    */\n    destroy(dom) { }\n}\n/**\nThe different types of blocks that can occur in an editor view.\n*/\nvar BlockType = /*@__PURE__*/(function (BlockType) {\n    /**\n    A line of text.\n    */\n    BlockType[BlockType[\"Text\"] = 0] = \"Text\";\n    /**\n    A block widget associated with the position after it.\n    */\n    BlockType[BlockType[\"WidgetBefore\"] = 1] = \"WidgetBefore\";\n    /**\n    A block widget associated with the position before it.\n    */\n    BlockType[BlockType[\"WidgetAfter\"] = 2] = \"WidgetAfter\";\n    /**\n    A block widget [replacing](https://codemirror.net/6/docs/ref/#view.Decoration^replace) a range of content.\n    */\n    BlockType[BlockType[\"WidgetRange\"] = 3] = \"WidgetRange\";\nreturn BlockType})(BlockType || (BlockType = {}));\n/**\nA decoration provides information on how to draw or style a piece\nof content. You'll usually use it wrapped in a\n[`Range`](https://codemirror.net/6/docs/ref/#state.Range), which adds a start and end position.\n@nonabstract\n*/\nclass Decoration extends _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.RangeValue {\n    constructor(\n    /**\n    @internal\n    */\n    startSide, \n    /**\n    @internal\n    */\n    endSide, \n    /**\n    @internal\n    */\n    widget, \n    /**\n    The config object used to create this decoration. You can\n    include additional properties in there to store metadata about\n    your decoration.\n    */\n    spec) {\n        super();\n        this.startSide = startSide;\n        this.endSide = endSide;\n        this.widget = widget;\n        this.spec = spec;\n    }\n    /**\n    @internal\n    */\n    get heightRelevant() { return false; }\n    /**\n    Create a mark decoration, which influences the styling of the\n    content in its range. Nested mark decorations will cause nested\n    DOM elements to be created. Nesting order is determined by\n    precedence of the [facet](https://codemirror.net/6/docs/ref/#view.EditorView^decorations), with\n    the higher-precedence decorations creating the inner DOM nodes.\n    Such elements are split on line boundaries and on the boundaries\n    of lower-precedence decorations.\n    */\n    static mark(spec) {\n        return new MarkDecoration(spec);\n    }\n    /**\n    Create a widget decoration, which displays a DOM element at the\n    given position.\n    */\n    static widget(spec) {\n        let side = Math.max(-10000, Math.min(10000, spec.side || 0)), block = !!spec.block;\n        side += (block && !spec.inlineOrder)\n            ? (side > 0 ? 300000000 /* Side.BlockAfter */ : -400000000 /* Side.BlockBefore */)\n            : (side > 0 ? 100000000 /* Side.InlineAfter */ : -100000000 /* Side.InlineBefore */);\n        return new PointDecoration(spec, side, side, block, spec.widget || null, false);\n    }\n    /**\n    Create a replace decoration which replaces the given range with\n    a widget, or simply hides it.\n    */\n    static replace(spec) {\n        let block = !!spec.block, startSide, endSide;\n        if (spec.isBlockGap) {\n            startSide = -500000000 /* Side.GapStart */;\n            endSide = 400000000 /* Side.GapEnd */;\n        }\n        else {\n            let { start, end } = getInclusive(spec, block);\n            startSide = (start ? (block ? -300000000 /* Side.BlockIncStart */ : -1 /* Side.InlineIncStart */) : 500000000 /* Side.NonIncStart */) - 1;\n            endSide = (end ? (block ? 200000000 /* Side.BlockIncEnd */ : 1 /* Side.InlineIncEnd */) : -600000000 /* Side.NonIncEnd */) + 1;\n        }\n        return new PointDecoration(spec, startSide, endSide, block, spec.widget || null, true);\n    }\n    /**\n    Create a line decoration, which can add DOM attributes to the\n    line starting at the given position.\n    */\n    static line(spec) {\n        return new LineDecoration(spec);\n    }\n    /**\n    Build a [`DecorationSet`](https://codemirror.net/6/docs/ref/#view.DecorationSet) from the given\n    decorated range or ranges. If the ranges aren't already sorted,\n    pass `true` for `sort` to make the library sort them for you.\n    */\n    static set(of, sort = false) {\n        return _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.RangeSet.of(of, sort);\n    }\n    /**\n    @internal\n    */\n    hasHeight() { return this.widget ? this.widget.estimatedHeight > -1 : false; }\n}\n/**\nThe empty set of decorations.\n*/\nDecoration.none = _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.RangeSet.empty;\nclass MarkDecoration extends Decoration {\n    constructor(spec) {\n        let { start, end } = getInclusive(spec);\n        super(start ? -1 /* Side.InlineIncStart */ : 500000000 /* Side.NonIncStart */, end ? 1 /* Side.InlineIncEnd */ : -600000000 /* Side.NonIncEnd */, null, spec);\n        this.tagName = spec.tagName || \"span\";\n        this.class = spec.class || \"\";\n        this.attrs = spec.attributes || null;\n    }\n    eq(other) {\n        var _a, _b;\n        return this == other ||\n            other instanceof MarkDecoration &&\n                this.tagName == other.tagName &&\n                (this.class || ((_a = this.attrs) === null || _a === void 0 ? void 0 : _a.class)) == (other.class || ((_b = other.attrs) === null || _b === void 0 ? void 0 : _b.class)) &&\n                attrsEq(this.attrs, other.attrs, \"class\");\n    }\n    range(from, to = from) {\n        if (from >= to)\n            throw new RangeError(\"Mark decorations may not be empty\");\n        return super.range(from, to);\n    }\n}\nMarkDecoration.prototype.point = false;\nclass LineDecoration extends Decoration {\n    constructor(spec) {\n        super(-200000000 /* Side.Line */, -200000000 /* Side.Line */, null, spec);\n    }\n    eq(other) {\n        return other instanceof LineDecoration &&\n            this.spec.class == other.spec.class &&\n            attrsEq(this.spec.attributes, other.spec.attributes);\n    }\n    range(from, to = from) {\n        if (to != from)\n            throw new RangeError(\"Line decoration ranges must be zero-length\");\n        return super.range(from, to);\n    }\n}\nLineDecoration.prototype.mapMode = _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.MapMode.TrackBefore;\nLineDecoration.prototype.point = true;\nclass PointDecoration extends Decoration {\n    constructor(spec, startSide, endSide, block, widget, isReplace) {\n        super(startSide, endSide, widget, spec);\n        this.block = block;\n        this.isReplace = isReplace;\n        this.mapMode = !block ? _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.MapMode.TrackDel : startSide <= 0 ? _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.MapMode.TrackBefore : _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.MapMode.TrackAfter;\n    }\n    // Only relevant when this.block == true\n    get type() {\n        return this.startSide != this.endSide ? BlockType.WidgetRange\n            : this.startSide <= 0 ? BlockType.WidgetBefore : BlockType.WidgetAfter;\n    }\n    get heightRelevant() {\n        return this.block || !!this.widget && (this.widget.estimatedHeight >= 5 || this.widget.lineBreaks > 0);\n    }\n    eq(other) {\n        return other instanceof PointDecoration &&\n            widgetsEq(this.widget, other.widget) &&\n            this.block == other.block &&\n            this.startSide == other.startSide && this.endSide == other.endSide;\n    }\n    range(from, to = from) {\n        if (this.isReplace && (from > to || (from == to && this.startSide > 0 && this.endSide <= 0)))\n            throw new RangeError(\"Invalid range for replacement decoration\");\n        if (!this.isReplace && to != from)\n            throw new RangeError(\"Widget decorations can only have zero-length ranges\");\n        return super.range(from, to);\n    }\n}\nPointDecoration.prototype.point = true;\nfunction getInclusive(spec, block = false) {\n    let { inclusiveStart: start, inclusiveEnd: end } = spec;\n    if (start == null)\n        start = spec.inclusive;\n    if (end == null)\n        end = spec.inclusive;\n    return { start: start !== null && start !== void 0 ? start : block, end: end !== null && end !== void 0 ? end : block };\n}\nfunction widgetsEq(a, b) {\n    return a == b || !!(a && b && a.compare(b));\n}\nfunction addRange(from, to, ranges, margin = 0) {\n    let last = ranges.length - 1;\n    if (last >= 0 && ranges[last] + margin >= from)\n        ranges[last] = Math.max(ranges[last], to);\n    else\n        ranges.push(from, to);\n}\n\nclass ContentBuilder {\n    constructor(doc, pos, end, disallowBlockEffectsFor) {\n        this.doc = doc;\n        this.pos = pos;\n        this.end = end;\n        this.disallowBlockEffectsFor = disallowBlockEffectsFor;\n        this.content = [];\n        this.curLine = null;\n        this.breakAtStart = 0;\n        this.pendingBuffer = 0 /* Buf.No */;\n        this.bufferMarks = [];\n        // Set to false directly after a widget that covers the position after it\n        this.atCursorPos = true;\n        this.openStart = -1;\n        this.openEnd = -1;\n        this.text = \"\";\n        this.textOff = 0;\n        this.cursor = doc.iter();\n        this.skip = pos;\n    }\n    posCovered() {\n        if (this.content.length == 0)\n            return !this.breakAtStart && this.doc.lineAt(this.pos).from != this.pos;\n        let last = this.content[this.content.length - 1];\n        return !(last.breakAfter || last instanceof BlockWidgetView && last.deco.endSide < 0);\n    }\n    getLine() {\n        if (!this.curLine) {\n            this.content.push(this.curLine = new LineView);\n            this.atCursorPos = true;\n        }\n        return this.curLine;\n    }\n    flushBuffer(active = this.bufferMarks) {\n        if (this.pendingBuffer) {\n            this.curLine.append(wrapMarks(new WidgetBufferView(-1), active), active.length);\n            this.pendingBuffer = 0 /* Buf.No */;\n        }\n    }\n    addBlockWidget(view) {\n        this.flushBuffer();\n        this.curLine = null;\n        this.content.push(view);\n    }\n    finish(openEnd) {\n        if (this.pendingBuffer && openEnd <= this.bufferMarks.length)\n            this.flushBuffer();\n        else\n            this.pendingBuffer = 0 /* Buf.No */;\n        if (!this.posCovered() &&\n            !(openEnd && this.content.length && this.content[this.content.length - 1] instanceof BlockWidgetView))\n            this.getLine();\n    }\n    buildText(length, active, openStart) {\n        while (length > 0) {\n            if (this.textOff == this.text.length) {\n                let { value, lineBreak, done } = this.cursor.next(this.skip);\n                this.skip = 0;\n                if (done)\n                    throw new Error(\"Ran out of text content when drawing inline views\");\n                if (lineBreak) {\n                    if (!this.posCovered())\n                        this.getLine();\n                    if (this.content.length)\n                        this.content[this.content.length - 1].breakAfter = 1;\n                    else\n                        this.breakAtStart = 1;\n                    this.flushBuffer();\n                    this.curLine = null;\n                    this.atCursorPos = true;\n                    length--;\n                    continue;\n                }\n                else {\n                    this.text = value;\n                    this.textOff = 0;\n                }\n            }\n            let take = Math.min(this.text.length - this.textOff, length, 512 /* T.Chunk */);\n            this.flushBuffer(active.slice(active.length - openStart));\n            this.getLine().append(wrapMarks(new TextView(this.text.slice(this.textOff, this.textOff + take)), active), openStart);\n            this.atCursorPos = true;\n            this.textOff += take;\n            length -= take;\n            openStart = 0;\n        }\n    }\n    span(from, to, active, openStart) {\n        this.buildText(to - from, active, openStart);\n        this.pos = to;\n        if (this.openStart < 0)\n            this.openStart = openStart;\n    }\n    point(from, to, deco, active, openStart, index) {\n        if (this.disallowBlockEffectsFor[index] && deco instanceof PointDecoration) {\n            if (deco.block)\n                throw new RangeError(\"Block decorations may not be specified via plugins\");\n            if (to > this.doc.lineAt(this.pos).to)\n                throw new RangeError(\"Decorations that replace line breaks may not be specified via plugins\");\n        }\n        let len = to - from;\n        if (deco instanceof PointDecoration) {\n            if (deco.block) {\n                if (deco.startSide > 0 && !this.posCovered())\n                    this.getLine();\n                this.addBlockWidget(new BlockWidgetView(deco.widget || NullWidget.block, len, deco));\n            }\n            else {\n                let view = WidgetView.create(deco.widget || NullWidget.inline, len, len ? 0 : deco.startSide);\n                let cursorBefore = this.atCursorPos && !view.isEditable && openStart <= active.length &&\n                    (from < to || deco.startSide > 0);\n                let cursorAfter = !view.isEditable && (from < to || openStart > active.length || deco.startSide <= 0);\n                let line = this.getLine();\n                if (this.pendingBuffer == 2 /* Buf.IfCursor */ && !cursorBefore && !view.isEditable)\n                    this.pendingBuffer = 0 /* Buf.No */;\n                this.flushBuffer(active);\n                if (cursorBefore) {\n                    line.append(wrapMarks(new WidgetBufferView(1), active), openStart);\n                    openStart = active.length + Math.max(0, openStart - active.length);\n                }\n                line.append(wrapMarks(view, active), openStart);\n                this.atCursorPos = cursorAfter;\n                this.pendingBuffer = !cursorAfter ? 0 /* Buf.No */ : from < to || openStart > active.length ? 1 /* Buf.Yes */ : 2 /* Buf.IfCursor */;\n                if (this.pendingBuffer)\n                    this.bufferMarks = active.slice();\n            }\n        }\n        else if (this.doc.lineAt(this.pos).from == this.pos) { // Line decoration\n            this.getLine().addLineDeco(deco);\n        }\n        if (len) {\n            // Advance the iterator past the replaced content\n            if (this.textOff + len <= this.text.length) {\n                this.textOff += len;\n            }\n            else {\n                this.skip += len - (this.text.length - this.textOff);\n                this.text = \"\";\n                this.textOff = 0;\n            }\n            this.pos = to;\n        }\n        if (this.openStart < 0)\n            this.openStart = openStart;\n    }\n    static build(text, from, to, decorations, dynamicDecorationMap) {\n        let builder = new ContentBuilder(text, from, to, dynamicDecorationMap);\n        builder.openEnd = _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.RangeSet.spans(decorations, from, to, builder);\n        if (builder.openStart < 0)\n            builder.openStart = builder.openEnd;\n        builder.finish(builder.openEnd);\n        return builder;\n    }\n}\nfunction wrapMarks(view, active) {\n    for (let mark of active)\n        view = new MarkView(mark, [view], view.length);\n    return view;\n}\nclass NullWidget extends WidgetType {\n    constructor(tag) {\n        super();\n        this.tag = tag;\n    }\n    eq(other) { return other.tag == this.tag; }\n    toDOM() { return document.createElement(this.tag); }\n    updateDOM(elt) { return elt.nodeName.toLowerCase() == this.tag; }\n    get isHidden() { return true; }\n}\nNullWidget.inline = /*@__PURE__*/new NullWidget(\"span\");\nNullWidget.block = /*@__PURE__*/new NullWidget(\"div\");\n\n/**\nUsed to indicate [text direction](https://codemirror.net/6/docs/ref/#view.EditorView.textDirection).\n*/\nvar Direction = /*@__PURE__*/(function (Direction) {\n    // (These are chosen to match the base levels, in bidi algorithm\n    // terms, of spans in that direction.)\n    /**\n    Left-to-right.\n    */\n    Direction[Direction[\"LTR\"] = 0] = \"LTR\";\n    /**\n    Right-to-left.\n    */\n    Direction[Direction[\"RTL\"] = 1] = \"RTL\";\nreturn Direction})(Direction || (Direction = {}));\nconst LTR = Direction.LTR, RTL = Direction.RTL;\n// Decode a string with each type encoded as log2(type)\nfunction dec(str) {\n    let result = [];\n    for (let i = 0; i < str.length; i++)\n        result.push(1 << +str[i]);\n    return result;\n}\n// Character types for codepoints 0 to 0xf8\nconst LowTypes = /*@__PURE__*/dec(\"88888888888888888888888888888888888666888888787833333333337888888000000000000000000000000008888880000000000000000000000000088888888888888888888888888888888888887866668888088888663380888308888800000000000000000000000800000000000000000000000000000008\");\n// Character types for codepoints 0x600 to 0x6f9\nconst ArabicTypes = /*@__PURE__*/dec(\"4444448826627288999999999992222222222222222222222222222222222222222222222229999999999999999999994444444444644222822222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222999999949999999229989999223333333333\");\nconst Brackets = /*@__PURE__*/Object.create(null), BracketStack = [];\n// There's a lot more in\n// https://www.unicode.org/Public/UCD/latest/ucd/BidiBrackets.txt,\n// which are left out to keep code size down.\nfor (let p of [\"()\", \"[]\", \"{}\"]) {\n    let l = /*@__PURE__*/p.charCodeAt(0), r = /*@__PURE__*/p.charCodeAt(1);\n    Brackets[l] = r;\n    Brackets[r] = -l;\n}\nfunction charType(ch) {\n    return ch <= 0xf7 ? LowTypes[ch] :\n        0x590 <= ch && ch <= 0x5f4 ? 2 /* T.R */ :\n            0x600 <= ch && ch <= 0x6f9 ? ArabicTypes[ch - 0x600] :\n                0x6ee <= ch && ch <= 0x8ac ? 4 /* T.AL */ :\n                    0x2000 <= ch && ch <= 0x200c ? 256 /* T.NI */ :\n                        0xfb50 <= ch && ch <= 0xfdff ? 4 /* T.AL */ : 1 /* T.L */;\n}\nconst BidiRE = /[\\u0590-\\u05f4\\u0600-\\u06ff\\u0700-\\u08ac\\ufb50-\\ufdff]/;\n/**\nRepresents a contiguous range of text that has a single direction\n(as in left-to-right or right-to-left).\n*/\nclass BidiSpan {\n    /**\n    The direction of this span.\n    */\n    get dir() { return this.level % 2 ? RTL : LTR; }\n    /**\n    @internal\n    */\n    constructor(\n    /**\n    The start of the span (relative to the start of the line).\n    */\n    from, \n    /**\n    The end of the span.\n    */\n    to, \n    /**\n    The [\"bidi\n    level\"](https://unicode.org/reports/tr9/#Basic_Display_Algorithm)\n    of the span (in this context, 0 means\n    left-to-right, 1 means right-to-left, 2 means left-to-right\n    number inside right-to-left text).\n    */\n    level) {\n        this.from = from;\n        this.to = to;\n        this.level = level;\n    }\n    /**\n    @internal\n    */\n    side(end, dir) { return (this.dir == dir) == end ? this.to : this.from; }\n    /**\n    @internal\n    */\n    forward(forward, dir) { return forward == (this.dir == dir); }\n    /**\n    @internal\n    */\n    static find(order, index, level, assoc) {\n        let maybe = -1;\n        for (let i = 0; i < order.length; i++) {\n            let span = order[i];\n            if (span.from <= index && span.to >= index) {\n                if (span.level == level)\n                    return i;\n                // When multiple spans match, if assoc != 0, take the one that\n                // covers that side, otherwise take the one with the minimum\n                // level.\n                if (maybe < 0 || (assoc != 0 ? (assoc < 0 ? span.from < index : span.to > index) : order[maybe].level > span.level))\n                    maybe = i;\n            }\n        }\n        if (maybe < 0)\n            throw new RangeError(\"Index out of range\");\n        return maybe;\n    }\n}\nfunction isolatesEq(a, b) {\n    if (a.length != b.length)\n        return false;\n    for (let i = 0; i < a.length; i++) {\n        let iA = a[i], iB = b[i];\n        if (iA.from != iB.from || iA.to != iB.to || iA.direction != iB.direction || !isolatesEq(iA.inner, iB.inner))\n            return false;\n    }\n    return true;\n}\n// Reused array of character types\nconst types = [];\n// Fill in the character types (in `types`) from `from` to `to` and\n// apply W normalization rules.\nfunction computeCharTypes(line, rFrom, rTo, isolates, outerType) {\n    for (let iI = 0; iI <= isolates.length; iI++) {\n        let from = iI ? isolates[iI - 1].to : rFrom, to = iI < isolates.length ? isolates[iI].from : rTo;\n        let prevType = iI ? 256 /* T.NI */ : outerType;\n        // W1. Examine each non-spacing mark (NSM) in the level run, and\n        // change the type of the NSM to the type of the previous\n        // character. If the NSM is at the start of the level run, it will\n        // get the type of sor.\n        // W2. Search backwards from each instance of a European number\n        // until the first strong type (R, L, AL, or sor) is found. If an\n        // AL is found, change the type of the European number to Arabic\n        // number.\n        // W3. Change all ALs to R.\n        // (Left after this: L, R, EN, AN, ET, CS, NI)\n        for (let i = from, prev = prevType, prevStrong = prevType; i < to; i++) {\n            let type = charType(line.charCodeAt(i));\n            if (type == 512 /* T.NSM */)\n                type = prev;\n            else if (type == 8 /* T.EN */ && prevStrong == 4 /* T.AL */)\n                type = 16 /* T.AN */;\n            types[i] = type == 4 /* T.AL */ ? 2 /* T.R */ : type;\n            if (type & 7 /* T.Strong */)\n                prevStrong = type;\n            prev = type;\n        }\n        // W5. A sequence of European terminators adjacent to European\n        // numbers changes to all European numbers.\n        // W6. Otherwise, separators and terminators change to Other\n        // Neutral.\n        // W7. Search backwards from each instance of a European number\n        // until the first strong type (R, L, or sor) is found. If an L is\n        // found, then change the type of the European number to L.\n        // (Left after this: L, R, EN+AN, NI)\n        for (let i = from, prev = prevType, prevStrong = prevType; i < to; i++) {\n            let type = types[i];\n            if (type == 128 /* T.CS */) {\n                if (i < to - 1 && prev == types[i + 1] && (prev & 24 /* T.Num */))\n                    type = types[i] = prev;\n                else\n                    types[i] = 256 /* T.NI */;\n            }\n            else if (type == 64 /* T.ET */) {\n                let end = i + 1;\n                while (end < to && types[end] == 64 /* T.ET */)\n                    end++;\n                let replace = (i && prev == 8 /* T.EN */) || (end < rTo && types[end] == 8 /* T.EN */) ? (prevStrong == 1 /* T.L */ ? 1 /* T.L */ : 8 /* T.EN */) : 256 /* T.NI */;\n                for (let j = i; j < end; j++)\n                    types[j] = replace;\n                i = end - 1;\n            }\n            else if (type == 8 /* T.EN */ && prevStrong == 1 /* T.L */) {\n                types[i] = 1 /* T.L */;\n            }\n            prev = type;\n            if (type & 7 /* T.Strong */)\n                prevStrong = type;\n        }\n    }\n}\n// Process brackets throughout a run sequence.\nfunction processBracketPairs(line, rFrom, rTo, isolates, outerType) {\n    let oppositeType = outerType == 1 /* T.L */ ? 2 /* T.R */ : 1 /* T.L */;\n    for (let iI = 0, sI = 0, context = 0; iI <= isolates.length; iI++) {\n        let from = iI ? isolates[iI - 1].to : rFrom, to = iI < isolates.length ? isolates[iI].from : rTo;\n        // N0. Process bracket pairs in an isolating run sequence\n        // sequentially in the logical order of the text positions of the\n        // opening paired brackets using the logic given below. Within this\n        // scope, bidirectional types EN and AN are treated as R.\n        for (let i = from, ch, br, type; i < to; i++) {\n            // Keeps [startIndex, type, strongSeen] triples for each open\n            // bracket on BracketStack.\n            if (br = Brackets[ch = line.charCodeAt(i)]) {\n                if (br < 0) { // Closing bracket\n                    for (let sJ = sI - 3; sJ >= 0; sJ -= 3) {\n                        if (BracketStack[sJ + 1] == -br) {\n                            let flags = BracketStack[sJ + 2];\n                            let type = (flags & 2 /* Bracketed.EmbedInside */) ? outerType :\n                                !(flags & 4 /* Bracketed.OppositeInside */) ? 0 :\n                                    (flags & 1 /* Bracketed.OppositeBefore */) ? oppositeType : outerType;\n                            if (type)\n                                types[i] = types[BracketStack[sJ]] = type;\n                            sI = sJ;\n                            break;\n                        }\n                    }\n                }\n                else if (BracketStack.length == 189 /* Bracketed.MaxDepth */) {\n                    break;\n                }\n                else {\n                    BracketStack[sI++] = i;\n                    BracketStack[sI++] = ch;\n                    BracketStack[sI++] = context;\n                }\n            }\n            else if ((type = types[i]) == 2 /* T.R */ || type == 1 /* T.L */) {\n                let embed = type == outerType;\n                context = embed ? 0 : 1 /* Bracketed.OppositeBefore */;\n                for (let sJ = sI - 3; sJ >= 0; sJ -= 3) {\n                    let cur = BracketStack[sJ + 2];\n                    if (cur & 2 /* Bracketed.EmbedInside */)\n                        break;\n                    if (embed) {\n                        BracketStack[sJ + 2] |= 2 /* Bracketed.EmbedInside */;\n                    }\n                    else {\n                        if (cur & 4 /* Bracketed.OppositeInside */)\n                            break;\n                        BracketStack[sJ + 2] |= 4 /* Bracketed.OppositeInside */;\n                    }\n                }\n            }\n        }\n    }\n}\nfunction processNeutrals(rFrom, rTo, isolates, outerType) {\n    for (let iI = 0, prev = outerType; iI <= isolates.length; iI++) {\n        let from = iI ? isolates[iI - 1].to : rFrom, to = iI < isolates.length ? isolates[iI].from : rTo;\n        // N1. A sequence of neutrals takes the direction of the\n        // surrounding strong text if the text on both sides has the same\n        // direction. European and Arabic numbers act as if they were R in\n        // terms of their influence on neutrals. Start-of-level-run (sor)\n        // and end-of-level-run (eor) are used at level run boundaries.\n        // N2. Any remaining neutrals take the embedding direction.\n        // (Left after this: L, R, EN+AN)\n        for (let i = from; i < to;) {\n            let type = types[i];\n            if (type == 256 /* T.NI */) {\n                let end = i + 1;\n                for (;;) {\n                    if (end == to) {\n                        if (iI == isolates.length)\n                            break;\n                        end = isolates[iI++].to;\n                        to = iI < isolates.length ? isolates[iI].from : rTo;\n                    }\n                    else if (types[end] == 256 /* T.NI */) {\n                        end++;\n                    }\n                    else {\n                        break;\n                    }\n                }\n                let beforeL = prev == 1 /* T.L */;\n                let afterL = (end < rTo ? types[end] : outerType) == 1 /* T.L */;\n                let replace = beforeL == afterL ? (beforeL ? 1 /* T.L */ : 2 /* T.R */) : outerType;\n                for (let j = end, jI = iI, fromJ = jI ? isolates[jI - 1].to : rFrom; j > i;) {\n                    if (j == fromJ) {\n                        j = isolates[--jI].from;\n                        fromJ = jI ? isolates[jI - 1].to : rFrom;\n                    }\n                    types[--j] = replace;\n                }\n                i = end;\n            }\n            else {\n                prev = type;\n                i++;\n            }\n        }\n    }\n}\n// Find the contiguous ranges of character types in a given range, and\n// emit spans for them. Flip the order of the spans as appropriate\n// based on the level, and call through to compute the spans for\n// isolates at the proper point.\nfunction emitSpans(line, from, to, level, baseLevel, isolates, order) {\n    let ourType = level % 2 ? 2 /* T.R */ : 1 /* T.L */;\n    if ((level % 2) == (baseLevel % 2)) { // Same dir as base direction, don't flip\n        for (let iCh = from, iI = 0; iCh < to;) {\n            // Scan a section of characters in direction ourType, unless\n            // there's another type of char right after iCh, in which case\n            // we scan a section of other characters (which, if ourType ==\n            // T.L, may contain both T.R and T.AN chars).\n            let sameDir = true, isNum = false;\n            if (iI == isolates.length || iCh < isolates[iI].from) {\n                let next = types[iCh];\n                if (next != ourType) {\n                    sameDir = false;\n                    isNum = next == 16 /* T.AN */;\n                }\n            }\n            // Holds an array of isolates to pass to a recursive call if we\n            // must recurse (to distinguish T.AN inside an RTL section in\n            // LTR text), null if we can emit directly\n            let recurse = !sameDir && ourType == 1 /* T.L */ ? [] : null;\n            let localLevel = sameDir ? level : level + 1;\n            let iScan = iCh;\n            run: for (;;) {\n                if (iI < isolates.length && iScan == isolates[iI].from) {\n                    if (isNum)\n                        break run;\n                    let iso = isolates[iI];\n                    // Scan ahead to verify that there is another char in this dir after the isolate(s)\n                    if (!sameDir)\n                        for (let upto = iso.to, jI = iI + 1;;) {\n                            if (upto == to)\n                                break run;\n                            if (jI < isolates.length && isolates[jI].from == upto)\n                                upto = isolates[jI++].to;\n                            else if (types[upto] == ourType)\n                                break run;\n                            else\n                                break;\n                        }\n                    iI++;\n                    if (recurse) {\n                        recurse.push(iso);\n                    }\n                    else {\n                        if (iso.from > iCh)\n                            order.push(new BidiSpan(iCh, iso.from, localLevel));\n                        let dirSwap = (iso.direction == LTR) != !(localLevel % 2);\n                        computeSectionOrder(line, dirSwap ? level + 1 : level, baseLevel, iso.inner, iso.from, iso.to, order);\n                        iCh = iso.to;\n                    }\n                    iScan = iso.to;\n                }\n                else if (iScan == to || (sameDir ? types[iScan] != ourType : types[iScan] == ourType)) {\n                    break;\n                }\n                else {\n                    iScan++;\n                }\n            }\n            if (recurse)\n                emitSpans(line, iCh, iScan, level + 1, baseLevel, recurse, order);\n            else if (iCh < iScan)\n                order.push(new BidiSpan(iCh, iScan, localLevel));\n            iCh = iScan;\n        }\n    }\n    else {\n        // Iterate in reverse to flip the span order. Same code again, but\n        // going from the back of the section to the front\n        for (let iCh = to, iI = isolates.length; iCh > from;) {\n            let sameDir = true, isNum = false;\n            if (!iI || iCh > isolates[iI - 1].to) {\n                let next = types[iCh - 1];\n                if (next != ourType) {\n                    sameDir = false;\n                    isNum = next == 16 /* T.AN */;\n                }\n            }\n            let recurse = !sameDir && ourType == 1 /* T.L */ ? [] : null;\n            let localLevel = sameDir ? level : level + 1;\n            let iScan = iCh;\n            run: for (;;) {\n                if (iI && iScan == isolates[iI - 1].to) {\n                    if (isNum)\n                        break run;\n                    let iso = isolates[--iI];\n                    // Scan ahead to verify that there is another char in this dir after the isolate(s)\n                    if (!sameDir)\n                        for (let upto = iso.from, jI = iI;;) {\n                            if (upto == from)\n                                break run;\n                            if (jI && isolates[jI - 1].to == upto)\n                                upto = isolates[--jI].from;\n                            else if (types[upto - 1] == ourType)\n                                break run;\n                            else\n                                break;\n                        }\n                    if (recurse) {\n                        recurse.push(iso);\n                    }\n                    else {\n                        if (iso.to < iCh)\n                            order.push(new BidiSpan(iso.to, iCh, localLevel));\n                        let dirSwap = (iso.direction == LTR) != !(localLevel % 2);\n                        computeSectionOrder(line, dirSwap ? level + 1 : level, baseLevel, iso.inner, iso.from, iso.to, order);\n                        iCh = iso.from;\n                    }\n                    iScan = iso.from;\n                }\n                else if (iScan == from || (sameDir ? types[iScan - 1] != ourType : types[iScan - 1] == ourType)) {\n                    break;\n                }\n                else {\n                    iScan--;\n                }\n            }\n            if (recurse)\n                emitSpans(line, iScan, iCh, level + 1, baseLevel, recurse, order);\n            else if (iScan < iCh)\n                order.push(new BidiSpan(iScan, iCh, localLevel));\n            iCh = iScan;\n        }\n    }\n}\nfunction computeSectionOrder(line, level, baseLevel, isolates, from, to, order) {\n    let outerType = (level % 2 ? 2 /* T.R */ : 1 /* T.L */);\n    computeCharTypes(line, from, to, isolates, outerType);\n    processBracketPairs(line, from, to, isolates, outerType);\n    processNeutrals(from, to, isolates, outerType);\n    emitSpans(line, from, to, level, baseLevel, isolates, order);\n}\nfunction computeOrder(line, direction, isolates) {\n    if (!line)\n        return [new BidiSpan(0, 0, direction == RTL ? 1 : 0)];\n    if (direction == LTR && !isolates.length && !BidiRE.test(line))\n        return trivialOrder(line.length);\n    if (isolates.length)\n        while (line.length > types.length)\n            types[types.length] = 256 /* T.NI */; // Make sure types array has no gaps\n    let order = [], level = direction == LTR ? 0 : 1;\n    computeSectionOrder(line, level, level, isolates, 0, line.length, order);\n    return order;\n}\nfunction trivialOrder(length) {\n    return [new BidiSpan(0, length, 0)];\n}\nlet movedOver = \"\";\n// This implementation moves strictly visually, without concern for a\n// traversal visiting every logical position in the string. It will\n// still do so for simple input, but situations like multiple isolates\n// with the same level next to each other, or text going against the\n// main dir at the end of the line, will make some positions\n// unreachable with this motion. Each visible cursor position will\n// correspond to the lower-level bidi span that touches it.\n//\n// The alternative would be to solve an order globally for a given\n// line, making sure that it includes every position, but that would\n// require associating non-canonical (higher bidi span level)\n// positions with a given visual position, which is likely to confuse\n// people. (And would generally be a lot more complicated.)\nfunction moveVisually(line, order, dir, start, forward) {\n    var _a;\n    let startIndex = start.head - line.from;\n    let spanI = BidiSpan.find(order, startIndex, (_a = start.bidiLevel) !== null && _a !== void 0 ? _a : -1, start.assoc);\n    let span = order[spanI], spanEnd = span.side(forward, dir);\n    // End of span\n    if (startIndex == spanEnd) {\n        let nextI = spanI += forward ? 1 : -1;\n        if (nextI < 0 || nextI >= order.length)\n            return null;\n        span = order[spanI = nextI];\n        startIndex = span.side(!forward, dir);\n        spanEnd = span.side(forward, dir);\n    }\n    let nextIndex = (0,_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.findClusterBreak)(line.text, startIndex, span.forward(forward, dir));\n    if (nextIndex < span.from || nextIndex > span.to)\n        nextIndex = spanEnd;\n    movedOver = line.text.slice(Math.min(startIndex, nextIndex), Math.max(startIndex, nextIndex));\n    let nextSpan = spanI == (forward ? order.length - 1 : 0) ? null : order[spanI + (forward ? 1 : -1)];\n    if (nextSpan && nextIndex == spanEnd && nextSpan.level + (forward ? 0 : 1) < span.level)\n        return _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.EditorSelection.cursor(nextSpan.side(!forward, dir) + line.from, nextSpan.forward(forward, dir) ? 1 : -1, nextSpan.level);\n    return _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.EditorSelection.cursor(nextIndex + line.from, span.forward(forward, dir) ? -1 : 1, span.level);\n}\nfunction autoDirection(text, from, to) {\n    for (let i = from; i < to; i++) {\n        let type = charType(text.charCodeAt(i));\n        if (type == 1 /* T.L */)\n            return LTR;\n        if (type == 2 /* T.R */ || type == 4 /* T.AL */)\n            return RTL;\n    }\n    return LTR;\n}\n\nconst clickAddsSelectionRange = /*@__PURE__*/_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.Facet.define();\nconst dragMovesSelection$1 = /*@__PURE__*/_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.Facet.define();\nconst mouseSelectionStyle = /*@__PURE__*/_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.Facet.define();\nconst exceptionSink = /*@__PURE__*/_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.Facet.define();\nconst updateListener = /*@__PURE__*/_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.Facet.define();\nconst inputHandler = /*@__PURE__*/_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.Facet.define();\nconst focusChangeEffect = /*@__PURE__*/_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.Facet.define();\nconst perLineTextDirection = /*@__PURE__*/_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.Facet.define({\n    combine: values => values.some(x => x)\n});\nconst nativeSelectionHidden = /*@__PURE__*/_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.Facet.define({\n    combine: values => values.some(x => x)\n});\nconst scrollHandler = /*@__PURE__*/_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.Facet.define();\nclass ScrollTarget {\n    constructor(range, y = \"nearest\", x = \"nearest\", yMargin = 5, xMargin = 5, \n    // This data structure is abused to also store precise scroll\n    // snapshots, instead of a `scrollIntoView` request. When this\n    // flag is `true`, `range` points at a position in the reference\n    // line, `yMargin` holds the difference between the top of that\n    // line and the top of the editor, and `xMargin` holds the\n    // editor's `scrollLeft`.\n    isSnapshot = false) {\n        this.range = range;\n        this.y = y;\n        this.x = x;\n        this.yMargin = yMargin;\n        this.xMargin = xMargin;\n        this.isSnapshot = isSnapshot;\n    }\n    map(changes) {\n        return changes.empty ? this :\n            new ScrollTarget(this.range.map(changes), this.y, this.x, this.yMargin, this.xMargin, this.isSnapshot);\n    }\n    clip(state) {\n        return this.range.to <= state.doc.length ? this :\n            new ScrollTarget(_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.EditorSelection.cursor(state.doc.length), this.y, this.x, this.yMargin, this.xMargin, this.isSnapshot);\n    }\n}\nconst scrollIntoView = /*@__PURE__*/_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.StateEffect.define({ map: (t, ch) => t.map(ch) });\nconst setEditContextFormatting = /*@__PURE__*/_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.StateEffect.define();\n/**\nLog or report an unhandled exception in client code. Should\nprobably only be used by extension code that allows client code to\nprovide functions, and calls those functions in a context where an\nexception can't be propagated to calling code in a reasonable way\n(for example when in an event handler).\n\nEither calls a handler registered with\n[`EditorView.exceptionSink`](https://codemirror.net/6/docs/ref/#view.EditorView^exceptionSink),\n`window.onerror`, if defined, or `console.error` (in which case\nit'll pass `context`, when given, as first argument).\n*/\nfunction logException(state, exception, context) {\n    let handler = state.facet(exceptionSink);\n    if (handler.length)\n        handler[0](exception);\n    else if (window.onerror)\n        window.onerror(String(exception), context, undefined, undefined, exception);\n    else if (context)\n        console.error(context + \":\", exception);\n    else\n        console.error(exception);\n}\nconst editable = /*@__PURE__*/_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.Facet.define({ combine: values => values.length ? values[0] : true });\nlet nextPluginID = 0;\nconst viewPlugin = /*@__PURE__*/_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.Facet.define();\n/**\nView plugins associate stateful values with a view. They can\ninfluence the way the content is drawn, and are notified of things\nthat happen in the view.\n*/\nclass ViewPlugin {\n    constructor(\n    /**\n    @internal\n    */\n    id, \n    /**\n    @internal\n    */\n    create, \n    /**\n    @internal\n    */\n    domEventHandlers, \n    /**\n    @internal\n    */\n    domEventObservers, buildExtensions) {\n        this.id = id;\n        this.create = create;\n        this.domEventHandlers = domEventHandlers;\n        this.domEventObservers = domEventObservers;\n        this.extension = buildExtensions(this);\n    }\n    /**\n    Define a plugin from a constructor function that creates the\n    plugin's value, given an editor view.\n    */\n    static define(create, spec) {\n        const { eventHandlers, eventObservers, provide, decorations: deco } = spec || {};\n        return new ViewPlugin(nextPluginID++, create, eventHandlers, eventObservers, plugin => {\n            let ext = [viewPlugin.of(plugin)];\n            if (deco)\n                ext.push(decorations.of(view => {\n                    let pluginInst = view.plugin(plugin);\n                    return pluginInst ? deco(pluginInst) : Decoration.none;\n                }));\n            if (provide)\n                ext.push(provide(plugin));\n            return ext;\n        });\n    }\n    /**\n    Create a plugin for a class whose constructor takes a single\n    editor view as argument.\n    */\n    static fromClass(cls, spec) {\n        return ViewPlugin.define(view => new cls(view), spec);\n    }\n}\nclass PluginInstance {\n    constructor(spec) {\n        this.spec = spec;\n        // When starting an update, all plugins have this field set to the\n        // update object, indicating they need to be updated. When finished\n        // updating, it is set to `false`. Retrieving a plugin that needs to\n        // be updated with `view.plugin` forces an eager update.\n        this.mustUpdate = null;\n        // This is null when the plugin is initially created, but\n        // initialized on the first update.\n        this.value = null;\n    }\n    update(view) {\n        if (!this.value) {\n            if (this.spec) {\n                try {\n                    this.value = this.spec.create(view);\n                }\n                catch (e) {\n                    logException(view.state, e, \"CodeMirror plugin crashed\");\n                    this.deactivate();\n                }\n            }\n        }\n        else if (this.mustUpdate) {\n            let update = this.mustUpdate;\n            this.mustUpdate = null;\n            if (this.value.update) {\n                try {\n                    this.value.update(update);\n                }\n                catch (e) {\n                    logException(update.state, e, \"CodeMirror plugin crashed\");\n                    if (this.value.destroy)\n                        try {\n                            this.value.destroy();\n                        }\n                        catch (_) { }\n                    this.deactivate();\n                }\n            }\n        }\n        return this;\n    }\n    destroy(view) {\n        var _a;\n        if ((_a = this.value) === null || _a === void 0 ? void 0 : _a.destroy) {\n            try {\n                this.value.destroy();\n            }\n            catch (e) {\n                logException(view.state, e, \"CodeMirror plugin crashed\");\n            }\n        }\n    }\n    deactivate() {\n        this.spec = this.value = null;\n    }\n}\nconst editorAttributes = /*@__PURE__*/_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.Facet.define();\nconst contentAttributes = /*@__PURE__*/_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.Facet.define();\n// Provide decorations\nconst decorations = /*@__PURE__*/_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.Facet.define();\nconst outerDecorations = /*@__PURE__*/_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.Facet.define();\nconst atomicRanges = /*@__PURE__*/_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.Facet.define();\nconst bidiIsolatedRanges = /*@__PURE__*/_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.Facet.define();\nfunction getIsolatedRanges(view, line) {\n    let isolates = view.state.facet(bidiIsolatedRanges);\n    if (!isolates.length)\n        return isolates;\n    let sets = isolates.map(i => i instanceof Function ? i(view) : i);\n    let result = [];\n    _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.RangeSet.spans(sets, line.from, line.to, {\n        point() { },\n        span(fromDoc, toDoc, active, open) {\n            let from = fromDoc - line.from, to = toDoc - line.from;\n            let level = result;\n            for (let i = active.length - 1; i >= 0; i--, open--) {\n                let direction = active[i].spec.bidiIsolate, update;\n                if (direction == null)\n                    direction = autoDirection(line.text, from, to);\n                if (open > 0 && level.length &&\n                    (update = level[level.length - 1]).to == from && update.direction == direction) {\n                    update.to = to;\n                    level = update.inner;\n                }\n                else {\n                    let add = { from, to, direction, inner: [] };\n                    level.push(add);\n                    level = add.inner;\n                }\n            }\n        }\n    });\n    return result;\n}\nconst scrollMargins = /*@__PURE__*/_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.Facet.define();\nfunction getScrollMargins(view) {\n    let left = 0, right = 0, top = 0, bottom = 0;\n    for (let source of view.state.facet(scrollMargins)) {\n        let m = source(view);\n        if (m) {\n            if (m.left != null)\n                left = Math.max(left, m.left);\n            if (m.right != null)\n                right = Math.max(right, m.right);\n            if (m.top != null)\n                top = Math.max(top, m.top);\n            if (m.bottom != null)\n                bottom = Math.max(bottom, m.bottom);\n        }\n    }\n    return { left, right, top, bottom };\n}\nconst styleModule = /*@__PURE__*/_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.Facet.define();\nclass ChangedRange {\n    constructor(fromA, toA, fromB, toB) {\n        this.fromA = fromA;\n        this.toA = toA;\n        this.fromB = fromB;\n        this.toB = toB;\n    }\n    join(other) {\n        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));\n    }\n    addToSet(set) {\n        let i = set.length, me = this;\n        for (; i > 0; i--) {\n            let range = set[i - 1];\n            if (range.fromA > me.toA)\n                continue;\n            if (range.toA < me.fromA)\n                break;\n            me = me.join(range);\n            set.splice(i - 1, 1);\n        }\n        set.splice(i, 0, me);\n        return set;\n    }\n    static extendWithRanges(diff, ranges) {\n        if (ranges.length == 0)\n            return diff;\n        let result = [];\n        for (let dI = 0, rI = 0, posA = 0, posB = 0;; dI++) {\n            let next = dI == diff.length ? null : diff[dI], off = posA - posB;\n            let end = next ? next.fromB : 1e9;\n            while (rI < ranges.length && ranges[rI] < end) {\n                let from = ranges[rI], to = ranges[rI + 1];\n                let fromB = Math.max(posB, from), toB = Math.min(end, to);\n                if (fromB <= toB)\n                    new ChangedRange(fromB + off, toB + off, fromB, toB).addToSet(result);\n                if (to > end)\n                    break;\n                else\n                    rI += 2;\n            }\n            if (!next)\n                return result;\n            new ChangedRange(next.fromA, next.toA, next.fromB, next.toB).addToSet(result);\n            posA = next.toA;\n            posB = next.toB;\n        }\n    }\n}\n/**\nView [plugins](https://codemirror.net/6/docs/ref/#view.ViewPlugin) are given instances of this\nclass, which describe what happened, whenever the view is updated.\n*/\nclass ViewUpdate {\n    constructor(\n    /**\n    The editor view that the update is associated with.\n    */\n    view, \n    /**\n    The new editor state.\n    */\n    state, \n    /**\n    The transactions involved in the update. May be empty.\n    */\n    transactions) {\n        this.view = view;\n        this.state = state;\n        this.transactions = transactions;\n        /**\n        @internal\n        */\n        this.flags = 0;\n        this.startState = view.state;\n        this.changes = _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.ChangeSet.empty(this.startState.doc.length);\n        for (let tr of transactions)\n            this.changes = this.changes.compose(tr.changes);\n        let changedRanges = [];\n        this.changes.iterChangedRanges((fromA, toA, fromB, toB) => changedRanges.push(new ChangedRange(fromA, toA, fromB, toB)));\n        this.changedRanges = changedRanges;\n    }\n    /**\n    @internal\n    */\n    static create(view, state, transactions) {\n        return new ViewUpdate(view, state, transactions);\n    }\n    /**\n    Tells you whether the [viewport](https://codemirror.net/6/docs/ref/#view.EditorView.viewport) or\n    [visible ranges](https://codemirror.net/6/docs/ref/#view.EditorView.visibleRanges) changed in this\n    update.\n    */\n    get viewportChanged() {\n        return (this.flags & 4 /* UpdateFlag.Viewport */) > 0;\n    }\n    /**\n    Indicates whether the height of a block element in the editor\n    changed in this update.\n    */\n    get heightChanged() {\n        return (this.flags & 2 /* UpdateFlag.Height */) > 0;\n    }\n    /**\n    Returns true when the document was modified or the size of the\n    editor, or elements within the editor, changed.\n    */\n    get geometryChanged() {\n        return this.docChanged || (this.flags & (8 /* UpdateFlag.Geometry */ | 2 /* UpdateFlag.Height */)) > 0;\n    }\n    /**\n    True when this update indicates a focus change.\n    */\n    get focusChanged() {\n        return (this.flags & 1 /* UpdateFlag.Focus */) > 0;\n    }\n    /**\n    Whether the document changed in this update.\n    */\n    get docChanged() {\n        return !this.changes.empty;\n    }\n    /**\n    Whether the selection was explicitly set in this update.\n    */\n    get selectionSet() {\n        return this.transactions.some(tr => tr.selection);\n    }\n    /**\n    @internal\n    */\n    get empty() { return this.flags == 0 && this.transactions.length == 0; }\n}\n\nclass DocView extends ContentView {\n    get length() { return this.view.state.doc.length; }\n    constructor(view) {\n        super();\n        this.view = view;\n        this.decorations = [];\n        this.dynamicDecorationMap = [false];\n        this.domChanged = null;\n        this.hasComposition = null;\n        this.markedForComposition = new Set;\n        this.editContextFormatting = Decoration.none;\n        this.lastCompositionAfterCursor = false;\n        // Track a minimum width for the editor. When measuring sizes in\n        // measureVisibleLineHeights, this is updated to point at the width\n        // of a given element and its extent in the document. When a change\n        // happens in that range, these are reset. That way, once we've seen\n        // a line/element of a given length, we keep the editor wide enough\n        // to fit at least that element, until it is changed, at which point\n        // we forget it again.\n        this.minWidth = 0;\n        this.minWidthFrom = 0;\n        this.minWidthTo = 0;\n        // Track whether the DOM selection was set in a lossy way, so that\n        // we don't mess it up when reading it back it\n        this.impreciseAnchor = null;\n        this.impreciseHead = null;\n        this.forceSelection = false;\n        // Used by the resize observer to ignore resizes that we caused\n        // ourselves\n        this.lastUpdate = Date.now();\n        this.setDOM(view.contentDOM);\n        this.children = [new LineView];\n        this.children[0].setParent(this);\n        this.updateDeco();\n        this.updateInner([new ChangedRange(0, 0, 0, view.state.doc.length)], 0, null);\n    }\n    // Update the document view to a given state.\n    update(update) {\n        var _a;\n        let changedRanges = update.changedRanges;\n        if (this.minWidth > 0 && changedRanges.length) {\n            if (!changedRanges.every(({ fromA, toA }) => toA < this.minWidthFrom || fromA > this.minWidthTo)) {\n                this.minWidth = this.minWidthFrom = this.minWidthTo = 0;\n            }\n            else {\n                this.minWidthFrom = update.changes.mapPos(this.minWidthFrom, 1);\n                this.minWidthTo = update.changes.mapPos(this.minWidthTo, 1);\n            }\n        }\n        this.updateEditContextFormatting(update);\n        let readCompositionAt = -1;\n        if (this.view.inputState.composing >= 0 && !this.view.observer.editContext) {\n            if ((_a = this.domChanged) === null || _a === void 0 ? void 0 : _a.newSel)\n                readCompositionAt = this.domChanged.newSel.head;\n            else if (!touchesComposition(update.changes, this.hasComposition) && !update.selectionSet)\n                readCompositionAt = update.state.selection.main.head;\n        }\n        let composition = readCompositionAt > -1 ? findCompositionRange(this.view, update.changes, readCompositionAt) : null;\n        this.domChanged = null;\n        if (this.hasComposition) {\n            this.markedForComposition.clear();\n            let { from, to } = this.hasComposition;\n            changedRanges = new ChangedRange(from, to, update.changes.mapPos(from, -1), update.changes.mapPos(to, 1))\n                .addToSet(changedRanges.slice());\n        }\n        this.hasComposition = composition ? { from: composition.range.fromB, to: composition.range.toB } : null;\n        // When the DOM nodes around the selection are moved to another\n        // parent, Chrome sometimes reports a different selection through\n        // getSelection than the one that it actually shows to the user.\n        // This forces a selection update when lines are joined to work\n        // around that. Issue #54\n        if ((browser.ie || browser.chrome) && !composition && update &&\n            update.state.doc.lines != update.startState.doc.lines)\n            this.forceSelection = true;\n        let prevDeco = this.decorations, deco = this.updateDeco();\n        let decoDiff = findChangedDeco(prevDeco, deco, update.changes);\n        changedRanges = ChangedRange.extendWithRanges(changedRanges, decoDiff);\n        if (!(this.flags & 7 /* ViewFlag.Dirty */) && changedRanges.length == 0) {\n            return false;\n        }\n        else {\n            this.updateInner(changedRanges, update.startState.doc.length, composition);\n            if (update.transactions.length)\n                this.lastUpdate = Date.now();\n            return true;\n        }\n    }\n    // Used by update and the constructor do perform the actual DOM\n    // update\n    updateInner(changes, oldLength, composition) {\n        this.view.viewState.mustMeasureContent = true;\n        this.updateChildren(changes, oldLength, composition);\n        let { observer } = this.view;\n        observer.ignore(() => {\n            // Lock the height during redrawing, since Chrome sometimes\n            // messes with the scroll position during DOM mutation (though\n            // no relayout is triggered and I cannot imagine how it can\n            // recompute the scroll position without a layout)\n            this.dom.style.height = this.view.viewState.contentHeight / this.view.scaleY + \"px\";\n            this.dom.style.flexBasis = this.minWidth ? this.minWidth + \"px\" : \"\";\n            // Chrome will sometimes, when DOM mutations occur directly\n            // around the selection, get confused and report a different\n            // selection from the one it displays (issue #218). This tries\n            // to detect that situation.\n            let track = browser.chrome || browser.ios ? { node: observer.selectionRange.focusNode, written: false } : undefined;\n            this.sync(this.view, track);\n            this.flags &= ~7 /* ViewFlag.Dirty */;\n            if (track && (track.written || observer.selectionRange.focusNode != track.node))\n                this.forceSelection = true;\n            this.dom.style.height = \"\";\n        });\n        this.markedForComposition.forEach(cView => cView.flags &= ~8 /* ViewFlag.Composition */);\n        let gaps = [];\n        if (this.view.viewport.from || this.view.viewport.to < this.view.state.doc.length)\n            for (let child of this.children)\n                if (child instanceof BlockWidgetView && child.widget instanceof BlockGapWidget)\n                    gaps.push(child.dom);\n        observer.updateGaps(gaps);\n    }\n    updateChildren(changes, oldLength, composition) {\n        let ranges = composition ? composition.range.addToSet(changes.slice()) : changes;\n        let cursor = this.childCursor(oldLength);\n        for (let i = ranges.length - 1;; i--) {\n            let next = i >= 0 ? ranges[i] : null;\n            if (!next)\n                break;\n            let { fromA, toA, fromB, toB } = next, content, breakAtStart, openStart, openEnd;\n            if (composition && composition.range.fromB < toB && composition.range.toB > fromB) {\n                let before = ContentBuilder.build(this.view.state.doc, fromB, composition.range.fromB, this.decorations, this.dynamicDecorationMap);\n                let after = ContentBuilder.build(this.view.state.doc, composition.range.toB, toB, this.decorations, this.dynamicDecorationMap);\n                breakAtStart = before.breakAtStart;\n                openStart = before.openStart;\n                openEnd = after.openEnd;\n                let compLine = this.compositionView(composition);\n                if (after.breakAtStart) {\n                    compLine.breakAfter = 1;\n                }\n                else if (after.content.length &&\n                    compLine.merge(compLine.length, compLine.length, after.content[0], false, after.openStart, 0)) {\n                    compLine.breakAfter = after.content[0].breakAfter;\n                    after.content.shift();\n                }\n                if (before.content.length &&\n                    compLine.merge(0, 0, before.content[before.content.length - 1], true, 0, before.openEnd)) {\n                    before.content.pop();\n                }\n                content = before.content.concat(compLine).concat(after.content);\n            }\n            else {\n                ({ content, breakAtStart, openStart, openEnd } =\n                    ContentBuilder.build(this.view.state.doc, fromB, toB, this.decorations, this.dynamicDecorationMap));\n            }\n            let { i: toI, off: toOff } = cursor.findPos(toA, 1);\n            let { i: fromI, off: fromOff } = cursor.findPos(fromA, -1);\n            replaceRange(this, fromI, fromOff, toI, toOff, content, breakAtStart, openStart, openEnd);\n        }\n        if (composition)\n            this.fixCompositionDOM(composition);\n    }\n    updateEditContextFormatting(update) {\n        this.editContextFormatting = this.editContextFormatting.map(update.changes);\n        for (let tr of update.transactions)\n            for (let effect of tr.effects)\n                if (effect.is(setEditContextFormatting)) {\n                    this.editContextFormatting = effect.value;\n                }\n    }\n    compositionView(composition) {\n        let cur = new TextView(composition.text.nodeValue);\n        cur.flags |= 8 /* ViewFlag.Composition */;\n        for (let { deco } of composition.marks)\n            cur = new MarkView(deco, [cur], cur.length);\n        let line = new LineView;\n        line.append(cur, 0);\n        return line;\n    }\n    fixCompositionDOM(composition) {\n        let fix = (dom, cView) => {\n            cView.flags |= 8 /* ViewFlag.Composition */ | (cView.children.some(c => c.flags & 7 /* ViewFlag.Dirty */) ? 1 /* ViewFlag.ChildDirty */ : 0);\n            this.markedForComposition.add(cView);\n            let prev = ContentView.get(dom);\n            if (prev && prev != cView)\n                prev.dom = null;\n            cView.setDOM(dom);\n        };\n        let pos = this.childPos(composition.range.fromB, 1);\n        let cView = this.children[pos.i];\n        fix(composition.line, cView);\n        for (let i = composition.marks.length - 1; i >= -1; i--) {\n            pos = cView.childPos(pos.off, 1);\n            cView = cView.children[pos.i];\n            fix(i >= 0 ? composition.marks[i].node : composition.text, cView);\n        }\n    }\n    // Sync the DOM selection to this.state.selection\n    updateSelection(mustRead = false, fromPointer = false) {\n        if (mustRead || !this.view.observer.selectionRange.focusNode)\n            this.view.observer.readSelectionRange();\n        let activeElt = this.view.root.activeElement, focused = activeElt == this.dom;\n        let selectionNotFocus = !focused &&\n            hasSelection(this.dom, this.view.observer.selectionRange) && !(activeElt && this.dom.contains(activeElt));\n        if (!(focused || fromPointer || selectionNotFocus))\n            return;\n        let force = this.forceSelection;\n        this.forceSelection = false;\n        let main = this.view.state.selection.main;\n        let anchor = this.moveToLine(this.domAtPos(main.anchor));\n        let head = main.empty ? anchor : this.moveToLine(this.domAtPos(main.head));\n        // Always reset on Firefox when next to an uneditable node to\n        // avoid invisible cursor bugs (#111)\n        if (browser.gecko && main.empty && !this.hasComposition && betweenUneditable(anchor)) {\n            let dummy = document.createTextNode(\"\");\n            this.view.observer.ignore(() => anchor.node.insertBefore(dummy, anchor.node.childNodes[anchor.offset] || null));\n            anchor = head = new DOMPos(dummy, 0);\n            force = true;\n        }\n        let domSel = this.view.observer.selectionRange;\n        // If the selection is already here, or in an equivalent position, don't touch it\n        if (force || !domSel.focusNode || (!isEquivalentPosition(anchor.node, anchor.offset, domSel.anchorNode, domSel.anchorOffset) ||\n            !isEquivalentPosition(head.node, head.offset, domSel.focusNode, domSel.focusOffset)) && !this.suppressWidgetCursorChange(domSel, main)) {\n            this.view.observer.ignore(() => {\n                // Chrome Android will hide the virtual keyboard when tapping\n                // inside an uneditable node, and not bring it back when we\n                // move the cursor to its proper position. This tries to\n                // restore the keyboard by cycling focus.\n                if (browser.android && browser.chrome && this.dom.contains(domSel.focusNode) &&\n                    inUneditable(domSel.focusNode, this.dom)) {\n                    this.dom.blur();\n                    this.dom.focus({ preventScroll: true });\n                }\n                let rawSel = getSelection(this.view.root);\n                if (!rawSel) ;\n                else if (main.empty) {\n                    // Work around https://bugzilla.mozilla.org/show_bug.cgi?id=1612076\n                    if (browser.gecko) {\n                        let nextTo = nextToUneditable(anchor.node, anchor.offset);\n                        if (nextTo && nextTo != (1 /* NextTo.Before */ | 2 /* NextTo.After */)) {\n                            let text = (nextTo == 1 /* NextTo.Before */ ? textNodeBefore : textNodeAfter)(anchor.node, anchor.offset);\n                            if (text)\n                                anchor = new DOMPos(text.node, text.offset);\n                        }\n                    }\n                    rawSel.collapse(anchor.node, anchor.offset);\n                    if (main.bidiLevel != null && rawSel.caretBidiLevel !== undefined)\n                        rawSel.caretBidiLevel = main.bidiLevel;\n                }\n                else if (rawSel.extend) {\n                    // Selection.extend can be used to create an 'inverted' selection\n                    // (one where the focus is before the anchor), but not all\n                    // browsers support it yet.\n                    rawSel.collapse(anchor.node, anchor.offset);\n                    // Safari will ignore the call above when the editor is\n                    // hidden, and then raise an error on the call to extend\n                    // (#940).\n                    try {\n                        rawSel.extend(head.node, head.offset);\n                    }\n                    catch (_) { }\n                }\n                else {\n                    // Primitive (IE) way\n                    let range = document.createRange();\n                    if (main.anchor > main.head)\n                        [anchor, head] = [head, anchor];\n                    range.setEnd(head.node, head.offset);\n                    range.setStart(anchor.node, anchor.offset);\n                    rawSel.removeAllRanges();\n                    rawSel.addRange(range);\n                }\n                if (selectionNotFocus && this.view.root.activeElement == this.dom) {\n                    this.dom.blur();\n                    if (activeElt)\n                        activeElt.focus();\n                }\n            });\n            this.view.observer.setSelectionRange(anchor, head);\n        }\n        this.impreciseAnchor = anchor.precise ? null : new DOMPos(domSel.anchorNode, domSel.anchorOffset);\n        this.impreciseHead = head.precise ? null : new DOMPos(domSel.focusNode, domSel.focusOffset);\n    }\n    // If a zero-length widget is inserted next to the cursor during\n    // composition, avoid moving it across it and disrupting the\n    // composition.\n    suppressWidgetCursorChange(sel, cursor) {\n        return this.hasComposition && cursor.empty &&\n            isEquivalentPosition(sel.focusNode, sel.focusOffset, sel.anchorNode, sel.anchorOffset) &&\n            this.posFromDOM(sel.focusNode, sel.focusOffset) == cursor.head;\n    }\n    enforceCursorAssoc() {\n        if (this.hasComposition)\n            return;\n        let { view } = this, cursor = view.state.selection.main;\n        let sel = getSelection(view.root);\n        let { anchorNode, anchorOffset } = view.observer.selectionRange;\n        if (!sel || !cursor.empty || !cursor.assoc || !sel.modify)\n            return;\n        let line = LineView.find(this, cursor.head);\n        if (!line)\n            return;\n        let lineStart = line.posAtStart;\n        if (cursor.head == lineStart || cursor.head == lineStart + line.length)\n            return;\n        let before = this.coordsAt(cursor.head, -1), after = this.coordsAt(cursor.head, 1);\n        if (!before || !after || before.bottom > after.top)\n            return;\n        let dom = this.domAtPos(cursor.head + cursor.assoc);\n        sel.collapse(dom.node, dom.offset);\n        sel.modify(\"move\", cursor.assoc < 0 ? \"forward\" : \"backward\", \"lineboundary\");\n        // This can go wrong in corner cases like single-character lines,\n        // so check and reset if necessary.\n        view.observer.readSelectionRange();\n        let newRange = view.observer.selectionRange;\n        if (view.docView.posFromDOM(newRange.anchorNode, newRange.anchorOffset) != cursor.from)\n            sel.collapse(anchorNode, anchorOffset);\n    }\n    // If a position is in/near a block widget, move it to a nearby text\n    // line, since we don't want the cursor inside a block widget.\n    moveToLine(pos) {\n        // Block widgets will return positions before/after them, which\n        // are thus directly in the document DOM element.\n        let dom = this.dom, newPos;\n        if (pos.node != dom)\n            return pos;\n        for (let i = pos.offset; !newPos && i < dom.childNodes.length; i++) {\n            let view = ContentView.get(dom.childNodes[i]);\n            if (view instanceof LineView)\n                newPos = view.domAtPos(0);\n        }\n        for (let i = pos.offset - 1; !newPos && i >= 0; i--) {\n            let view = ContentView.get(dom.childNodes[i]);\n            if (view instanceof LineView)\n                newPos = view.domAtPos(view.length);\n        }\n        return newPos ? new DOMPos(newPos.node, newPos.offset, true) : pos;\n    }\n    nearest(dom) {\n        for (let cur = dom; cur;) {\n            let domView = ContentView.get(cur);\n            if (domView && domView.rootView == this)\n                return domView;\n            cur = cur.parentNode;\n        }\n        return null;\n    }\n    posFromDOM(node, offset) {\n        let view = this.nearest(node);\n        if (!view)\n            throw new RangeError(\"Trying to find position for a DOM position outside of the document\");\n        return view.localPosFromDOM(node, offset) + view.posAtStart;\n    }\n    domAtPos(pos) {\n        let { i, off } = this.childCursor().findPos(pos, -1);\n        for (; i < this.children.length - 1;) {\n            let child = this.children[i];\n            if (off < child.length || child instanceof LineView)\n                break;\n            i++;\n            off = 0;\n        }\n        return this.children[i].domAtPos(off);\n    }\n    coordsAt(pos, side) {\n        let best = null, bestPos = 0;\n        for (let off = this.length, i = this.children.length - 1; i >= 0; i--) {\n            let child = this.children[i], end = off - child.breakAfter, start = end - child.length;\n            if (end < pos)\n                break;\n            if (start <= pos && (start < pos || child.covers(-1)) && (end > pos || child.covers(1)) &&\n                (!best || child instanceof LineView && !(best instanceof LineView && side >= 0))) {\n                best = child;\n                bestPos = start;\n            }\n            else if (best && start == pos && end == pos && child instanceof BlockWidgetView && Math.abs(side) < 2) {\n                if (child.deco.startSide < 0)\n                    break;\n                else if (i)\n                    best = null;\n            }\n            off = start;\n        }\n        return best ? best.coordsAt(pos - bestPos, side) : null;\n    }\n    coordsForChar(pos) {\n        let { i, off } = this.childPos(pos, 1), child = this.children[i];\n        if (!(child instanceof LineView))\n            return null;\n        while (child.children.length) {\n            let { i, off: childOff } = child.childPos(off, 1);\n            for (;; i++) {\n                if (i == child.children.length)\n                    return null;\n                if ((child = child.children[i]).length)\n                    break;\n            }\n            off = childOff;\n        }\n        if (!(child instanceof TextView))\n            return null;\n        let end = (0,_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.findClusterBreak)(child.text, off);\n        if (end == off)\n            return null;\n        let rects = textRange(child.dom, off, end).getClientRects();\n        for (let i = 0; i < rects.length; i++) {\n            let rect = rects[i];\n            if (i == rects.length - 1 || rect.top < rect.bottom && rect.left < rect.right)\n                return rect;\n        }\n        return null;\n    }\n    measureVisibleLineHeights(viewport) {\n        let result = [], { from, to } = viewport;\n        let contentWidth = this.view.contentDOM.clientWidth;\n        let isWider = contentWidth > Math.max(this.view.scrollDOM.clientWidth, this.minWidth) + 1;\n        let widest = -1, ltr = this.view.textDirection == Direction.LTR;\n        for (let pos = 0, i = 0; i < this.children.length; i++) {\n            let child = this.children[i], end = pos + child.length;\n            if (end > to)\n                break;\n            if (pos >= from) {\n                let childRect = child.dom.getBoundingClientRect();\n                result.push(childRect.height);\n                if (isWider) {\n                    let last = child.dom.lastChild;\n                    let rects = last ? clientRectsFor(last) : [];\n                    if (rects.length) {\n                        let rect = rects[rects.length - 1];\n                        let width = ltr ? rect.right - childRect.left : childRect.right - rect.left;\n                        if (width > widest) {\n                            widest = width;\n                            this.minWidth = contentWidth;\n                            this.minWidthFrom = pos;\n                            this.minWidthTo = end;\n                        }\n                    }\n                }\n            }\n            pos = end + child.breakAfter;\n        }\n        return result;\n    }\n    textDirectionAt(pos) {\n        let { i } = this.childPos(pos, 1);\n        return getComputedStyle(this.children[i].dom).direction == \"rtl\" ? Direction.RTL : Direction.LTR;\n    }\n    measureTextSize() {\n        for (let child of this.children) {\n            if (child instanceof LineView) {\n                let measure = child.measureTextSize();\n                if (measure)\n                    return measure;\n            }\n        }\n        // If no workable line exists, force a layout of a measurable element\n        let dummy = document.createElement(\"div\"), lineHeight, charWidth, textHeight;\n        dummy.className = \"cm-line\";\n        dummy.style.width = \"99999px\";\n        dummy.style.position = \"absolute\";\n        dummy.textContent = \"abc def ghi jkl mno pqr stu\";\n        this.view.observer.ignore(() => {\n            this.dom.appendChild(dummy);\n            let rect = clientRectsFor(dummy.firstChild)[0];\n            lineHeight = dummy.getBoundingClientRect().height;\n            charWidth = rect ? rect.width / 27 : 7;\n            textHeight = rect ? rect.height : lineHeight;\n            dummy.remove();\n        });\n        return { lineHeight, charWidth, textHeight };\n    }\n    childCursor(pos = this.length) {\n        // Move back to start of last element when possible, so that\n        // `ChildCursor.findPos` doesn't have to deal with the edge case\n        // of being after the last element.\n        let i = this.children.length;\n        if (i)\n            pos -= this.children[--i].length;\n        return new ChildCursor(this.children, pos, i);\n    }\n    computeBlockGapDeco() {\n        let deco = [], vs = this.view.viewState;\n        for (let pos = 0, i = 0;; i++) {\n            let next = i == vs.viewports.length ? null : vs.viewports[i];\n            let end = next ? next.from - 1 : this.length;\n            if (end > pos) {\n                let height = (vs.lineBlockAt(end).bottom - vs.lineBlockAt(pos).top) / this.view.scaleY;\n                deco.push(Decoration.replace({\n                    widget: new BlockGapWidget(height),\n                    block: true,\n                    inclusive: true,\n                    isBlockGap: true,\n                }).range(pos, end));\n            }\n            if (!next)\n                break;\n            pos = next.to + 1;\n        }\n        return Decoration.set(deco);\n    }\n    updateDeco() {\n        let i = 1;\n        let allDeco = this.view.state.facet(decorations).map(d => {\n            let dynamic = this.dynamicDecorationMap[i++] = typeof d == \"function\";\n            return dynamic ? d(this.view) : d;\n        });\n        let dynamicOuter = false, outerDeco = this.view.state.facet(outerDecorations).map((d, i) => {\n            let dynamic = typeof d == \"function\";\n            if (dynamic)\n                dynamicOuter = true;\n            return dynamic ? d(this.view) : d;\n        });\n        if (outerDeco.length) {\n            this.dynamicDecorationMap[i++] = dynamicOuter;\n            allDeco.push(_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.RangeSet.join(outerDeco));\n        }\n        this.decorations = [\n            this.editContextFormatting,\n            ...allDeco,\n            this.computeBlockGapDeco(),\n            this.view.viewState.lineGapDeco\n        ];\n        while (i < this.decorations.length)\n            this.dynamicDecorationMap[i++] = false;\n        return this.decorations;\n    }\n    scrollIntoView(target) {\n        if (target.isSnapshot) {\n            let ref = this.view.viewState.lineBlockAt(target.range.head);\n            this.view.scrollDOM.scrollTop = ref.top - target.yMargin;\n            this.view.scrollDOM.scrollLeft = target.xMargin;\n            return;\n        }\n        for (let handler of this.view.state.facet(scrollHandler)) {\n            try {\n                if (handler(this.view, target.range, target))\n                    return true;\n            }\n            catch (e) {\n                logException(this.view.state, e, \"scroll handler\");\n            }\n        }\n        let { range } = target;\n        let rect = this.coordsAt(range.head, range.empty ? range.assoc : range.head > range.anchor ? -1 : 1), other;\n        if (!rect)\n            return;\n        if (!range.empty && (other = this.coordsAt(range.anchor, range.anchor > range.head ? -1 : 1)))\n            rect = { left: Math.min(rect.left, other.left), top: Math.min(rect.top, other.top),\n                right: Math.max(rect.right, other.right), bottom: Math.max(rect.bottom, other.bottom) };\n        let margins = getScrollMargins(this.view);\n        let targetRect = {\n            left: rect.left - margins.left, top: rect.top - margins.top,\n            right: rect.right + margins.right, bottom: rect.bottom + margins.bottom\n        };\n        let { offsetWidth, offsetHeight } = this.view.scrollDOM;\n        scrollRectIntoView(this.view.scrollDOM, targetRect, range.head < range.anchor ? -1 : 1, target.x, target.y, Math.max(Math.min(target.xMargin, offsetWidth), -offsetWidth), Math.max(Math.min(target.yMargin, offsetHeight), -offsetHeight), this.view.textDirection == Direction.LTR);\n    }\n}\nfunction betweenUneditable(pos) {\n    return pos.node.nodeType == 1 && pos.node.firstChild &&\n        (pos.offset == 0 || pos.node.childNodes[pos.offset - 1].contentEditable == \"false\") &&\n        (pos.offset == pos.node.childNodes.length || pos.node.childNodes[pos.offset].contentEditable == \"false\");\n}\nclass BlockGapWidget extends WidgetType {\n    constructor(height) {\n        super();\n        this.height = height;\n    }\n    toDOM() {\n        let elt = document.createElement(\"div\");\n        elt.className = \"cm-gap\";\n        this.updateDOM(elt);\n        return elt;\n    }\n    eq(other) { return other.height == this.height; }\n    updateDOM(elt) {\n        elt.style.height = this.height + \"px\";\n        return true;\n    }\n    get editable() { return true; }\n    get estimatedHeight() { return this.height; }\n    ignoreEvent() { return false; }\n}\nfunction findCompositionNode(view, headPos) {\n    let sel = view.observer.selectionRange;\n    if (!sel.focusNode)\n        return null;\n    let textBefore = textNodeBefore(sel.focusNode, sel.focusOffset);\n    let textAfter = textNodeAfter(sel.focusNode, sel.focusOffset);\n    let textNode = textBefore || textAfter;\n    if (textAfter && textBefore && textAfter.node != textBefore.node) {\n        let descAfter = ContentView.get(textAfter.node);\n        if (!descAfter || descAfter instanceof TextView && descAfter.text != textAfter.node.nodeValue) {\n            textNode = textAfter;\n        }\n        else if (view.docView.lastCompositionAfterCursor) {\n            let descBefore = ContentView.get(textBefore.node);\n            if (!(!descBefore || descBefore instanceof TextView && descBefore.text != textBefore.node.nodeValue))\n                textNode = textAfter;\n        }\n    }\n    view.docView.lastCompositionAfterCursor = textNode != textBefore;\n    if (!textNode)\n        return null;\n    let from = headPos - textNode.offset;\n    return { from, to: from + textNode.node.nodeValue.length, node: textNode.node };\n}\nfunction findCompositionRange(view, changes, headPos) {\n    let found = findCompositionNode(view, headPos);\n    if (!found)\n        return null;\n    let { node: textNode, from, to } = found, text = textNode.nodeValue;\n    // Don't try to preserve multi-line compositions\n    if (/[\\n\\r]/.test(text))\n        return null;\n    if (view.state.doc.sliceString(found.from, found.to) != text)\n        return null;\n    let inv = changes.invertedDesc;\n    let range = new ChangedRange(inv.mapPos(from), inv.mapPos(to), from, to);\n    let marks = [];\n    for (let parent = textNode.parentNode;; parent = parent.parentNode) {\n        let parentView = ContentView.get(parent);\n        if (parentView instanceof MarkView)\n            marks.push({ node: parent, deco: parentView.mark });\n        else if (parentView instanceof LineView || parent.nodeName == \"DIV\" && parent.parentNode == view.contentDOM)\n            return { range, text: textNode, marks, line: parent };\n        else if (parent != view.contentDOM)\n            marks.push({ node: parent, deco: new MarkDecoration({\n                    inclusive: true,\n                    attributes: getAttrs(parent),\n                    tagName: parent.tagName.toLowerCase()\n                }) });\n        else\n            return null;\n    }\n}\nfunction nextToUneditable(node, offset) {\n    if (node.nodeType != 1)\n        return 0;\n    return (offset && node.childNodes[offset - 1].contentEditable == \"false\" ? 1 /* NextTo.Before */ : 0) |\n        (offset < node.childNodes.length && node.childNodes[offset].contentEditable == \"false\" ? 2 /* NextTo.After */ : 0);\n}\nlet DecorationComparator$1 = class DecorationComparator {\n    constructor() {\n        this.changes = [];\n    }\n    compareRange(from, to) { addRange(from, to, this.changes); }\n    comparePoint(from, to) { addRange(from, to, this.changes); }\n};\nfunction findChangedDeco(a, b, diff) {\n    let comp = new DecorationComparator$1;\n    _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.RangeSet.compare(a, b, diff, comp);\n    return comp.changes;\n}\nfunction inUneditable(node, inside) {\n    for (let cur = node; cur && cur != inside; cur = cur.assignedSlot || cur.parentNode) {\n        if (cur.nodeType == 1 && cur.contentEditable == 'false') {\n            return true;\n        }\n    }\n    return false;\n}\nfunction touchesComposition(changes, composition) {\n    let touched = false;\n    if (composition)\n        changes.iterChangedRanges((from, to) => {\n            if (from < composition.to && to > composition.from)\n                touched = true;\n        });\n    return touched;\n}\n\nfunction groupAt(state, pos, bias = 1) {\n    let categorize = state.charCategorizer(pos);\n    let line = state.doc.lineAt(pos), linePos = pos - line.from;\n    if (line.length == 0)\n        return _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.EditorSelection.cursor(pos);\n    if (linePos == 0)\n        bias = 1;\n    else if (linePos == line.length)\n        bias = -1;\n    let from = linePos, to = linePos;\n    if (bias < 0)\n        from = (0,_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.findClusterBreak)(line.text, linePos, false);\n    else\n        to = (0,_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.findClusterBreak)(line.text, linePos);\n    let cat = categorize(line.text.slice(from, to));\n    while (from > 0) {\n        let prev = (0,_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.findClusterBreak)(line.text, from, false);\n        if (categorize(line.text.slice(prev, from)) != cat)\n            break;\n        from = prev;\n    }\n    while (to < line.length) {\n        let next = (0,_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.findClusterBreak)(line.text, to);\n        if (categorize(line.text.slice(to, next)) != cat)\n            break;\n        to = next;\n    }\n    return _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.EditorSelection.range(from + line.from, to + line.from);\n}\n// Search the DOM for the {node, offset} position closest to the given\n// coordinates. Very inefficient and crude, but can usually be avoided\n// by calling caret(Position|Range)FromPoint instead.\nfunction getdx(x, rect) {\n    return rect.left > x ? rect.left - x : Math.max(0, x - rect.right);\n}\nfunction getdy(y, rect) {\n    return rect.top > y ? rect.top - y : Math.max(0, y - rect.bottom);\n}\nfunction yOverlap(a, b) {\n    return a.top < b.bottom - 1 && a.bottom > b.top + 1;\n}\nfunction upTop(rect, top) {\n    return top < rect.top ? { top, left: rect.left, right: rect.right, bottom: rect.bottom } : rect;\n}\nfunction upBot(rect, bottom) {\n    return bottom > rect.bottom ? { top: rect.top, left: rect.left, right: rect.right, bottom } : rect;\n}\nfunction domPosAtCoords(parent, x, y) {\n    let closest, closestRect, closestX, closestY, closestOverlap = false;\n    let above, below, aboveRect, belowRect;\n    for (let child = parent.firstChild; child; child = child.nextSibling) {\n        let rects = clientRectsFor(child);\n        for (let i = 0; i < rects.length; i++) {\n            let rect = rects[i];\n            if (closestRect && yOverlap(closestRect, rect))\n                rect = upTop(upBot(rect, closestRect.bottom), closestRect.top);\n            let dx = getdx(x, rect), dy = getdy(y, rect);\n            if (dx == 0 && dy == 0)\n                return child.nodeType == 3 ? domPosInText(child, x, y) : domPosAtCoords(child, x, y);\n            if (!closest || closestY > dy || closestY == dy && closestX > dx) {\n                closest = child;\n                closestRect = rect;\n                closestX = dx;\n                closestY = dy;\n                let side = dy ? (y < rect.top ? -1 : 1) : dx ? (x < rect.left ? -1 : 1) : 0;\n                closestOverlap = !side || (side > 0 ? i < rects.length - 1 : i > 0);\n            }\n            if (dx == 0) {\n                if (y > rect.bottom && (!aboveRect || aboveRect.bottom < rect.bottom)) {\n                    above = child;\n                    aboveRect = rect;\n                }\n                else if (y < rect.top && (!belowRect || belowRect.top > rect.top)) {\n                    below = child;\n                    belowRect = rect;\n                }\n            }\n            else if (aboveRect && yOverlap(aboveRect, rect)) {\n                aboveRect = upBot(aboveRect, rect.bottom);\n            }\n            else if (belowRect && yOverlap(belowRect, rect)) {\n                belowRect = upTop(belowRect, rect.top);\n            }\n        }\n    }\n    if (aboveRect && aboveRect.bottom >= y) {\n        closest = above;\n        closestRect = aboveRect;\n    }\n    else if (belowRect && belowRect.top <= y) {\n        closest = below;\n        closestRect = belowRect;\n    }\n    if (!closest)\n        return { node: parent, offset: 0 };\n    let clipX = Math.max(closestRect.left, Math.min(closestRect.right, x));\n    if (closest.nodeType == 3)\n        return domPosInText(closest, clipX, y);\n    if (closestOverlap && closest.contentEditable != \"false\")\n        return domPosAtCoords(closest, clipX, y);\n    let offset = Array.prototype.indexOf.call(parent.childNodes, closest) +\n        (x >= (closestRect.left + closestRect.right) / 2 ? 1 : 0);\n    return { node: parent, offset };\n}\nfunction domPosInText(node, x, y) {\n    let len = node.nodeValue.length;\n    let closestOffset = -1, closestDY = 1e9, generalSide = 0;\n    for (let i = 0; i < len; i++) {\n        let rects = textRange(node, i, i + 1).getClientRects();\n        for (let j = 0; j < rects.length; j++) {\n            let rect = rects[j];\n            if (rect.top == rect.bottom)\n                continue;\n            if (!generalSide)\n                generalSide = x - rect.left;\n            let dy = (rect.top > y ? rect.top - y : y - rect.bottom) - 1;\n            if (rect.left - 1 <= x && rect.right + 1 >= x && dy < closestDY) {\n                let right = x >= (rect.left + rect.right) / 2, after = right;\n                if (browser.chrome || browser.gecko) {\n                    // Check for RTL on browsers that support getting client\n                    // rects for empty ranges.\n                    let rectBefore = textRange(node, i).getBoundingClientRect();\n                    if (rectBefore.left == rect.right)\n                        after = !right;\n                }\n                if (dy <= 0)\n                    return { node, offset: i + (after ? 1 : 0) };\n                closestOffset = i + (after ? 1 : 0);\n                closestDY = dy;\n            }\n        }\n    }\n    return { node, offset: closestOffset > -1 ? closestOffset : generalSide > 0 ? node.nodeValue.length : 0 };\n}\nfunction posAtCoords(view, coords, precise, bias = -1) {\n    var _a, _b;\n    let content = view.contentDOM.getBoundingClientRect(), docTop = content.top + view.viewState.paddingTop;\n    let block, { docHeight } = view.viewState;\n    let { x, y } = coords, yOffset = y - docTop;\n    if (yOffset < 0)\n        return 0;\n    if (yOffset > docHeight)\n        return view.state.doc.length;\n    // Scan for a text block near the queried y position\n    for (let halfLine = view.viewState.heightOracle.textHeight / 2, bounced = false;;) {\n        block = view.elementAtHeight(yOffset);\n        if (block.type == BlockType.Text)\n            break;\n        for (;;) {\n            // Move the y position out of this block\n            yOffset = bias > 0 ? block.bottom + halfLine : block.top - halfLine;\n            if (yOffset >= 0 && yOffset <= docHeight)\n                break;\n            // If the document consists entirely of replaced widgets, we\n            // won't find a text block, so return 0\n            if (bounced)\n                return precise ? null : 0;\n            bounced = true;\n            bias = -bias;\n        }\n    }\n    y = docTop + yOffset;\n    let lineStart = block.from;\n    // If this is outside of the rendered viewport, we can't determine a position\n    if (lineStart < view.viewport.from)\n        return view.viewport.from == 0 ? 0 : precise ? null : posAtCoordsImprecise(view, content, block, x, y);\n    if (lineStart > view.viewport.to)\n        return view.viewport.to == view.state.doc.length ? view.state.doc.length :\n            precise ? null : posAtCoordsImprecise(view, content, block, x, y);\n    // Prefer ShadowRootOrDocument.elementFromPoint if present, fall back to document if not\n    let doc = view.dom.ownerDocument;\n    let root = view.root.elementFromPoint ? view.root : doc;\n    let element = root.elementFromPoint(x, y);\n    if (element && !view.contentDOM.contains(element))\n        element = null;\n    // If the element is unexpected, clip x at the sides of the content area and try again\n    if (!element) {\n        x = Math.max(content.left + 1, Math.min(content.right - 1, x));\n        element = root.elementFromPoint(x, y);\n        if (element && !view.contentDOM.contains(element))\n            element = null;\n    }\n    // There's visible editor content under the point, so we can try\n    // using caret(Position|Range)FromPoint as a shortcut\n    let node, offset = -1;\n    if (element && ((_a = view.docView.nearest(element)) === null || _a === void 0 ? void 0 : _a.isEditable) != false) {\n        if (doc.caretPositionFromPoint) {\n            let pos = doc.caretPositionFromPoint(x, y);\n            if (pos)\n                ({ offsetNode: node, offset } = pos);\n        }\n        else if (doc.caretRangeFromPoint) {\n            let range = doc.caretRangeFromPoint(x, y);\n            if (range) {\n                ({ startContainer: node, startOffset: offset } = range);\n                if (!view.contentDOM.contains(node) ||\n                    browser.safari && isSuspiciousSafariCaretResult(node, offset, x) ||\n                    browser.chrome && isSuspiciousChromeCaretResult(node, offset, x))\n                    node = undefined;\n            }\n        }\n    }\n    // No luck, do our own (potentially expensive) search\n    if (!node || !view.docView.dom.contains(node)) {\n        let line = LineView.find(view.docView, lineStart);\n        if (!line)\n            return yOffset > block.top + block.height / 2 ? block.to : block.from;\n        ({ node, offset } = domPosAtCoords(line.dom, x, y));\n    }\n    let nearest = view.docView.nearest(node);\n    if (!nearest)\n        return null;\n    if (nearest.isWidget && ((_b = nearest.dom) === null || _b === void 0 ? void 0 : _b.nodeType) == 1) {\n        let rect = nearest.dom.getBoundingClientRect();\n        return coords.y < rect.top || coords.y <= rect.bottom && coords.x <= (rect.left + rect.right) / 2\n            ? nearest.posAtStart : nearest.posAtEnd;\n    }\n    else {\n        return nearest.localPosFromDOM(node, offset) + nearest.posAtStart;\n    }\n}\nfunction posAtCoordsImprecise(view, contentRect, block, x, y) {\n    let into = Math.round((x - contentRect.left) * view.defaultCharacterWidth);\n    if (view.lineWrapping && block.height > view.defaultLineHeight * 1.5) {\n        let textHeight = view.viewState.heightOracle.textHeight;\n        let line = Math.floor((y - block.top - (view.defaultLineHeight - textHeight) * 0.5) / textHeight);\n        into += line * view.viewState.heightOracle.lineLength;\n    }\n    let content = view.state.sliceDoc(block.from, block.to);\n    return block.from + (0,_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.findColumn)(content, into, view.state.tabSize);\n}\n// In case of a high line height, Safari's caretRangeFromPoint treats\n// the space between lines as belonging to the last character of the\n// line before. This is used to detect such a result so that it can be\n// ignored (issue #401).\nfunction isSuspiciousSafariCaretResult(node, offset, x) {\n    let len;\n    if (node.nodeType != 3 || offset != (len = node.nodeValue.length))\n        return false;\n    for (let next = node.nextSibling; next; next = next.nextSibling)\n        if (next.nodeType != 1 || next.nodeName != \"BR\")\n            return false;\n    return textRange(node, len - 1, len).getBoundingClientRect().left > x;\n}\n// Chrome will move positions between lines to the start of the next line\nfunction isSuspiciousChromeCaretResult(node, offset, x) {\n    if (offset != 0)\n        return false;\n    for (let cur = node;;) {\n        let parent = cur.parentNode;\n        if (!parent || parent.nodeType != 1 || parent.firstChild != cur)\n            return false;\n        if (parent.classList.contains(\"cm-line\"))\n            break;\n        cur = parent;\n    }\n    let rect = node.nodeType == 1 ? node.getBoundingClientRect()\n        : textRange(node, 0, Math.max(node.nodeValue.length, 1)).getBoundingClientRect();\n    return x - rect.left > 5;\n}\nfunction blockAt(view, pos) {\n    let line = view.lineBlockAt(pos);\n    if (Array.isArray(line.type))\n        for (let l of line.type) {\n            if (l.to > pos || l.to == pos && (l.to == line.to || l.type == BlockType.Text))\n                return l;\n        }\n    return line;\n}\nfunction moveToLineBoundary(view, start, forward, includeWrap) {\n    let line = blockAt(view, start.head);\n    let coords = !includeWrap || line.type != BlockType.Text || !(view.lineWrapping || line.widgetLineBreaks) ? null\n        : view.coordsAtPos(start.assoc < 0 && start.head > line.from ? start.head - 1 : start.head);\n    if (coords) {\n        let editorRect = view.dom.getBoundingClientRect();\n        let direction = view.textDirectionAt(line.from);\n        let pos = view.posAtCoords({ x: forward == (direction == Direction.LTR) ? editorRect.right - 1 : editorRect.left + 1,\n            y: (coords.top + coords.bottom) / 2 });\n        if (pos != null)\n            return _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.EditorSelection.cursor(pos, forward ? -1 : 1);\n    }\n    return _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.EditorSelection.cursor(forward ? line.to : line.from, forward ? -1 : 1);\n}\nfunction moveByChar(view, start, forward, by) {\n    let line = view.state.doc.lineAt(start.head), spans = view.bidiSpans(line);\n    let direction = view.textDirectionAt(line.from);\n    for (let cur = start, check = null;;) {\n        let next = moveVisually(line, spans, direction, cur, forward), char = movedOver;\n        if (!next) {\n            if (line.number == (forward ? view.state.doc.lines : 1))\n                return cur;\n            char = \"\\n\";\n            line = view.state.doc.line(line.number + (forward ? 1 : -1));\n            spans = view.bidiSpans(line);\n            next = view.visualLineSide(line, !forward);\n        }\n        if (!check) {\n            if (!by)\n                return next;\n            check = by(char);\n        }\n        else if (!check(char)) {\n            return cur;\n        }\n        cur = next;\n    }\n}\nfunction byGroup(view, pos, start) {\n    let categorize = view.state.charCategorizer(pos);\n    let cat = categorize(start);\n    return (next) => {\n        let nextCat = categorize(next);\n        if (cat == _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.CharCategory.Space)\n            cat = nextCat;\n        return cat == nextCat;\n    };\n}\nfunction moveVertically(view, start, forward, distance) {\n    let startPos = start.head, dir = forward ? 1 : -1;\n    if (startPos == (forward ? view.state.doc.length : 0))\n        return _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.EditorSelection.cursor(startPos, start.assoc);\n    let goal = start.goalColumn, startY;\n    let rect = view.contentDOM.getBoundingClientRect();\n    let startCoords = view.coordsAtPos(startPos, start.assoc || -1), docTop = view.documentTop;\n    if (startCoords) {\n        if (goal == null)\n            goal = startCoords.left - rect.left;\n        startY = dir < 0 ? startCoords.top : startCoords.bottom;\n    }\n    else {\n        let line = view.viewState.lineBlockAt(startPos);\n        if (goal == null)\n            goal = Math.min(rect.right - rect.left, view.defaultCharacterWidth * (startPos - line.from));\n        startY = (dir < 0 ? line.top : line.bottom) + docTop;\n    }\n    let resolvedGoal = rect.left + goal;\n    let dist = distance !== null && distance !== void 0 ? distance : (view.viewState.heightOracle.textHeight >> 1);\n    for (let extra = 0;; extra += 10) {\n        let curY = startY + (dist + extra) * dir;\n        let pos = posAtCoords(view, { x: resolvedGoal, y: curY }, false, dir);\n        if (curY < rect.top || curY > rect.bottom || (dir < 0 ? pos < startPos : pos > startPos)) {\n            let charRect = view.docView.coordsForChar(pos);\n            let assoc = !charRect || curY < charRect.top ? -1 : 1;\n            return _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.EditorSelection.cursor(pos, assoc, undefined, goal);\n        }\n    }\n}\nfunction skipAtomicRanges(atoms, pos, bias) {\n    for (;;) {\n        let moved = 0;\n        for (let set of atoms) {\n            set.between(pos - 1, pos + 1, (from, to, value) => {\n                if (pos > from && pos < to) {\n                    let side = moved || bias || (pos - from < to - pos ? -1 : 1);\n                    pos = side < 0 ? from : to;\n                    moved = side;\n                }\n            });\n        }\n        if (!moved)\n            return pos;\n    }\n}\nfunction skipAtoms(view, oldPos, pos) {\n    let newPos = skipAtomicRanges(view.state.facet(atomicRanges).map(f => f(view)), pos.from, oldPos.head > pos.from ? -1 : 1);\n    return newPos == pos.from ? pos : _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.EditorSelection.cursor(newPos, newPos < pos.from ? 1 : -1);\n}\n\n// This will also be where dragging info and such goes\nclass InputState {\n    setSelectionOrigin(origin) {\n        this.lastSelectionOrigin = origin;\n        this.lastSelectionTime = Date.now();\n    }\n    constructor(view) {\n        this.view = view;\n        this.lastKeyCode = 0;\n        this.lastKeyTime = 0;\n        this.lastTouchTime = 0;\n        this.lastFocusTime = 0;\n        this.lastScrollTop = 0;\n        this.lastScrollLeft = 0;\n        // On iOS, some keys need to have their default behavior happen\n        // (after which we retroactively handle them and reset the DOM) to\n        // avoid messing up the virtual keyboard state.\n        this.pendingIOSKey = undefined;\n        /**\n        When enabled (>-1), tab presses are not given to key handlers,\n        leaving the browser's default behavior. If >0, the mode expires\n        at that timestamp, and any other keypress clears it.\n        Esc enables temporary tab focus mode for two seconds when not\n        otherwise handled.\n        */\n        this.tabFocusMode = -1;\n        this.lastSelectionOrigin = null;\n        this.lastSelectionTime = 0;\n        this.lastContextMenu = 0;\n        this.scrollHandlers = [];\n        this.handlers = Object.create(null);\n        // -1 means not in a composition. Otherwise, this counts the number\n        // of changes made during the composition. The count is used to\n        // avoid treating the start state of the composition, before any\n        // changes have been made, as part of the composition.\n        this.composing = -1;\n        // Tracks whether the next change should be marked as starting the\n        // composition (null means no composition, true means next is the\n        // first, false means first has already been marked for this\n        // composition)\n        this.compositionFirstChange = null;\n        // End time of the previous composition\n        this.compositionEndedAt = 0;\n        // Used in a kludge to detect when an Enter keypress should be\n        // considered part of the composition on Safari, which fires events\n        // in the wrong order\n        this.compositionPendingKey = false;\n        // Used to categorize changes as part of a composition, even when\n        // the mutation events fire shortly after the compositionend event\n        this.compositionPendingChange = false;\n        this.mouseSelection = null;\n        // When a drag from the editor is active, this points at the range\n        // being dragged.\n        this.draggedContent = null;\n        this.handleEvent = this.handleEvent.bind(this);\n        this.notifiedFocused = view.hasFocus;\n        // On Safari adding an input event handler somehow prevents an\n        // issue where the composition vanishes when you press enter.\n        if (browser.safari)\n            view.contentDOM.addEventListener(\"input\", () => null);\n        if (browser.gecko)\n            firefoxCopyCutHack(view.contentDOM.ownerDocument);\n    }\n    handleEvent(event) {\n        if (!eventBelongsToEditor(this.view, event) || this.ignoreDuringComposition(event))\n            return;\n        if (event.type == \"keydown\" && this.keydown(event))\n            return;\n        this.runHandlers(event.type, event);\n    }\n    runHandlers(type, event) {\n        let handlers = this.handlers[type];\n        if (handlers) {\n            for (let observer of handlers.observers)\n                observer(this.view, event);\n            for (let handler of handlers.handlers) {\n                if (event.defaultPrevented)\n                    break;\n                if (handler(this.view, event)) {\n                    event.preventDefault();\n                    break;\n                }\n            }\n        }\n    }\n    ensureHandlers(plugins) {\n        let handlers = computeHandlers(plugins), prev = this.handlers, dom = this.view.contentDOM;\n        for (let type in handlers)\n            if (type != \"scroll\") {\n                let passive = !handlers[type].handlers.length;\n                let exists = prev[type];\n                if (exists && passive != !exists.handlers.length) {\n                    dom.removeEventListener(type, this.handleEvent);\n                    exists = null;\n                }\n                if (!exists)\n                    dom.addEventListener(type, this.handleEvent, { passive });\n            }\n        for (let type in prev)\n            if (type != \"scroll\" && !handlers[type])\n                dom.removeEventListener(type, this.handleEvent);\n        this.handlers = handlers;\n    }\n    keydown(event) {\n        // Must always run, even if a custom handler handled the event\n        this.lastKeyCode = event.keyCode;\n        this.lastKeyTime = Date.now();\n        if (event.keyCode == 9 && this.tabFocusMode > -1 && (!this.tabFocusMode || Date.now() <= this.tabFocusMode))\n            return true;\n        if (this.tabFocusMode > 0 && event.keyCode != 27 && modifierCodes.indexOf(event.keyCode) < 0)\n            this.tabFocusMode = -1;\n        // Chrome for Android usually doesn't fire proper key events, but\n        // occasionally does, usually surrounded by a bunch of complicated\n        // composition changes. When an enter or backspace key event is\n        // seen, hold off on handling DOM events for a bit, and then\n        // dispatch it.\n        if (browser.android && browser.chrome && !event.synthetic &&\n            (event.keyCode == 13 || event.keyCode == 8)) {\n            this.view.observer.delayAndroidKey(event.key, event.keyCode);\n            return true;\n        }\n        // Preventing the default behavior of Enter on iOS makes the\n        // virtual keyboard get stuck in the wrong (lowercase)\n        // state. So we let it go through, and then, in\n        // applyDOMChange, notify key handlers of it and reset to\n        // the state they produce.\n        let pending;\n        if (browser.ios && !event.synthetic && !event.altKey && !event.metaKey &&\n            ((pending = PendingKeys.find(key => key.keyCode == event.keyCode)) && !event.ctrlKey ||\n                EmacsyPendingKeys.indexOf(event.key) > -1 && event.ctrlKey && !event.shiftKey)) {\n            this.pendingIOSKey = pending || event;\n            setTimeout(() => this.flushIOSKey(), 250);\n            return true;\n        }\n        if (event.keyCode != 229)\n            this.view.observer.forceFlush();\n        return false;\n    }\n    flushIOSKey(change) {\n        let key = this.pendingIOSKey;\n        if (!key)\n            return false;\n        // This looks like an autocorrection before Enter\n        if (key.key == \"Enter\" && change && change.from < change.to && /^\\S+$/.test(change.insert.toString()))\n            return false;\n        this.pendingIOSKey = undefined;\n        return dispatchKey(this.view.contentDOM, key.key, key.keyCode, key instanceof KeyboardEvent ? key : undefined);\n    }\n    ignoreDuringComposition(event) {\n        if (!/^key/.test(event.type))\n            return false;\n        if (this.composing > 0)\n            return true;\n        // See https://www.stum.de/2016/06/24/handling-ime-events-in-javascript/.\n        // On some input method editors (IMEs), the Enter key is used to\n        // confirm character selection. On Safari, when Enter is pressed,\n        // compositionend and keydown events are sometimes emitted in the\n        // wrong order. The key event should still be ignored, even when\n        // it happens after the compositionend event.\n        if (browser.safari && !browser.ios && this.compositionPendingKey && Date.now() - this.compositionEndedAt < 100) {\n            this.compositionPendingKey = false;\n            return true;\n        }\n        return false;\n    }\n    startMouseSelection(mouseSelection) {\n        if (this.mouseSelection)\n            this.mouseSelection.destroy();\n        this.mouseSelection = mouseSelection;\n    }\n    update(update) {\n        this.view.observer.update(update);\n        if (this.mouseSelection)\n            this.mouseSelection.update(update);\n        if (this.draggedContent && update.docChanged)\n            this.draggedContent = this.draggedContent.map(update.changes);\n        if (update.transactions.length)\n            this.lastKeyCode = this.lastSelectionTime = 0;\n    }\n    destroy() {\n        if (this.mouseSelection)\n            this.mouseSelection.destroy();\n    }\n}\nfunction bindHandler(plugin, handler) {\n    return (view, event) => {\n        try {\n            return handler.call(plugin, event, view);\n        }\n        catch (e) {\n            logException(view.state, e);\n        }\n    };\n}\nfunction computeHandlers(plugins) {\n    let result = Object.create(null);\n    function record(type) {\n        return result[type] || (result[type] = { observers: [], handlers: [] });\n    }\n    for (let plugin of plugins) {\n        let spec = plugin.spec;\n        if (spec && spec.domEventHandlers)\n            for (let type in spec.domEventHandlers) {\n                let f = spec.domEventHandlers[type];\n                if (f)\n                    record(type).handlers.push(bindHandler(plugin.value, f));\n            }\n        if (spec && spec.domEventObservers)\n            for (let type in spec.domEventObservers) {\n                let f = spec.domEventObservers[type];\n                if (f)\n                    record(type).observers.push(bindHandler(plugin.value, f));\n            }\n    }\n    for (let type in handlers)\n        record(type).handlers.push(handlers[type]);\n    for (let type in observers)\n        record(type).observers.push(observers[type]);\n    return result;\n}\nconst PendingKeys = [\n    { key: \"Backspace\", keyCode: 8, inputType: \"deleteContentBackward\" },\n    { key: \"Enter\", keyCode: 13, inputType: \"insertParagraph\" },\n    { key: \"Enter\", keyCode: 13, inputType: \"insertLineBreak\" },\n    { key: \"Delete\", keyCode: 46, inputType: \"deleteContentForward\" }\n];\nconst EmacsyPendingKeys = \"dthko\";\n// Key codes for modifier keys\nconst modifierCodes = [16, 17, 18, 20, 91, 92, 224, 225];\nconst dragScrollMargin = 6;\nfunction dragScrollSpeed(dist) {\n    return Math.max(0, dist) * 0.7 + 8;\n}\nfunction dist(a, b) {\n    return Math.max(Math.abs(a.clientX - b.clientX), Math.abs(a.clientY - b.clientY));\n}\nclass MouseSelection {\n    constructor(view, startEvent, style, mustSelect) {\n        this.view = view;\n        this.startEvent = startEvent;\n        this.style = style;\n        this.mustSelect = mustSelect;\n        this.scrollSpeed = { x: 0, y: 0 };\n        this.scrolling = -1;\n        this.lastEvent = startEvent;\n        this.scrollParent = scrollableParent(view.contentDOM);\n        this.atoms = view.state.facet(atomicRanges).map(f => f(view));\n        let doc = view.contentDOM.ownerDocument;\n        doc.addEventListener(\"mousemove\", this.move = this.move.bind(this));\n        doc.addEventListener(\"mouseup\", this.up = this.up.bind(this));\n        this.extend = startEvent.shiftKey;\n        this.multiple = view.state.facet(_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.EditorState.allowMultipleSelections) && addsSelectionRange(view, startEvent);\n        this.dragging = isInPrimarySelection(view, startEvent) && getClickType(startEvent) == 1 ? null : false;\n    }\n    start(event) {\n        // When clicking outside of the selection, immediately apply the\n        // effect of starting the selection\n        if (this.dragging === false)\n            this.select(event);\n    }\n    move(event) {\n        var _a;\n        if (event.buttons == 0)\n            return this.destroy();\n        if (this.dragging || this.dragging == null && dist(this.startEvent, event) < 10)\n            return;\n        this.select(this.lastEvent = event);\n        let sx = 0, sy = 0;\n        let rect = ((_a = this.scrollParent) === null || _a === void 0 ? void 0 : _a.getBoundingClientRect())\n            || { left: 0, top: 0, right: this.view.win.innerWidth, bottom: this.view.win.innerHeight };\n        let margins = getScrollMargins(this.view);\n        if (event.clientX - margins.left <= rect.left + dragScrollMargin)\n            sx = -dragScrollSpeed(rect.left - event.clientX);\n        else if (event.clientX + margins.right >= rect.right - dragScrollMargin)\n            sx = dragScrollSpeed(event.clientX - rect.right);\n        if (event.clientY - margins.top <= rect.top + dragScrollMargin)\n            sy = -dragScrollSpeed(rect.top - event.clientY);\n        else if (event.clientY + margins.bottom >= rect.bottom - dragScrollMargin)\n            sy = dragScrollSpeed(event.clientY - rect.bottom);\n        this.setScrollSpeed(sx, sy);\n    }\n    up(event) {\n        if (this.dragging == null)\n            this.select(this.lastEvent);\n        if (!this.dragging)\n            event.preventDefault();\n        this.destroy();\n    }\n    destroy() {\n        this.setScrollSpeed(0, 0);\n        let doc = this.view.contentDOM.ownerDocument;\n        doc.removeEventListener(\"mousemove\", this.move);\n        doc.removeEventListener(\"mouseup\", this.up);\n        this.view.inputState.mouseSelection = this.view.inputState.draggedContent = null;\n    }\n    setScrollSpeed(sx, sy) {\n        this.scrollSpeed = { x: sx, y: sy };\n        if (sx || sy) {\n            if (this.scrolling < 0)\n                this.scrolling = setInterval(() => this.scroll(), 50);\n        }\n        else if (this.scrolling > -1) {\n            clearInterval(this.scrolling);\n            this.scrolling = -1;\n        }\n    }\n    scroll() {\n        if (this.scrollParent) {\n            this.scrollParent.scrollLeft += this.scrollSpeed.x;\n            this.scrollParent.scrollTop += this.scrollSpeed.y;\n        }\n        else {\n            this.view.win.scrollBy(this.scrollSpeed.x, this.scrollSpeed.y);\n        }\n        if (this.dragging === false)\n            this.select(this.lastEvent);\n    }\n    skipAtoms(sel) {\n        let ranges = null;\n        for (let i = 0; i < sel.ranges.length; i++) {\n            let range = sel.ranges[i], updated = null;\n            if (range.empty) {\n                let pos = skipAtomicRanges(this.atoms, range.from, 0);\n                if (pos != range.from)\n                    updated = _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.EditorSelection.cursor(pos, -1);\n            }\n            else {\n                let from = skipAtomicRanges(this.atoms, range.from, -1);\n                let to = skipAtomicRanges(this.atoms, range.to, 1);\n                if (from != range.from || to != range.to)\n                    updated = _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.EditorSelection.range(range.from == range.anchor ? from : to, range.from == range.head ? from : to);\n            }\n            if (updated) {\n                if (!ranges)\n                    ranges = sel.ranges.slice();\n                ranges[i] = updated;\n            }\n        }\n        return ranges ? _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.EditorSelection.create(ranges, sel.mainIndex) : sel;\n    }\n    select(event) {\n        let { view } = this, selection = this.skipAtoms(this.style.get(event, this.extend, this.multiple));\n        if (this.mustSelect || !selection.eq(view.state.selection, this.dragging === false))\n            this.view.dispatch({\n                selection,\n                userEvent: \"select.pointer\"\n            });\n        this.mustSelect = false;\n    }\n    update(update) {\n        if (update.transactions.some(tr => tr.isUserEvent(\"input.type\")))\n            this.destroy();\n        else if (this.style.update(update))\n            setTimeout(() => this.select(this.lastEvent), 20);\n    }\n}\nfunction addsSelectionRange(view, event) {\n    let facet = view.state.facet(clickAddsSelectionRange);\n    return facet.length ? facet[0](event) : browser.mac ? event.metaKey : event.ctrlKey;\n}\nfunction dragMovesSelection(view, event) {\n    let facet = view.state.facet(dragMovesSelection$1);\n    return facet.length ? facet[0](event) : browser.mac ? !event.altKey : !event.ctrlKey;\n}\nfunction isInPrimarySelection(view, event) {\n    let { main } = view.state.selection;\n    if (main.empty)\n        return false;\n    // On boundary clicks, check whether the coordinates are inside the\n    // selection's client rectangles\n    let sel = getSelection(view.root);\n    if (!sel || sel.rangeCount == 0)\n        return true;\n    let rects = sel.getRangeAt(0).getClientRects();\n    for (let i = 0; i < rects.length; i++) {\n        let rect = rects[i];\n        if (rect.left <= event.clientX && rect.right >= event.clientX &&\n            rect.top <= event.clientY && rect.bottom >= event.clientY)\n            return true;\n    }\n    return false;\n}\nfunction eventBelongsToEditor(view, event) {\n    if (!event.bubbles)\n        return true;\n    if (event.defaultPrevented)\n        return false;\n    for (let node = event.target, cView; node != view.contentDOM; node = node.parentNode)\n        if (!node || node.nodeType == 11 || ((cView = ContentView.get(node)) && cView.ignoreEvent(event)))\n            return false;\n    return true;\n}\nconst handlers = /*@__PURE__*/Object.create(null);\nconst observers = /*@__PURE__*/Object.create(null);\n// This is very crude, but unfortunately both these browsers _pretend_\n// that they have a clipboard API—all the objects and methods are\n// there, they just don't work, and they are hard to test.\nconst brokenClipboardAPI = (browser.ie && browser.ie_version < 15) ||\n    (browser.ios && browser.webkit_version < 604);\nfunction capturePaste(view) {\n    let parent = view.dom.parentNode;\n    if (!parent)\n        return;\n    let target = parent.appendChild(document.createElement(\"textarea\"));\n    target.style.cssText = \"position: fixed; left: -10000px; top: 10px\";\n    target.focus();\n    setTimeout(() => {\n        view.focus();\n        target.remove();\n        doPaste(view, target.value);\n    }, 50);\n}\nfunction doPaste(view, input) {\n    let { state } = view, changes, i = 1, text = state.toText(input);\n    let byLine = text.lines == state.selection.ranges.length;\n    let linewise = lastLinewiseCopy != null && state.selection.ranges.every(r => r.empty) && lastLinewiseCopy == text.toString();\n    if (linewise) {\n        let lastLine = -1;\n        changes = state.changeByRange(range => {\n            let line = state.doc.lineAt(range.from);\n            if (line.from == lastLine)\n                return { range };\n            lastLine = line.from;\n            let insert = state.toText((byLine ? text.line(i++).text : input) + state.lineBreak);\n            return { changes: { from: line.from, insert },\n                range: _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.EditorSelection.cursor(range.from + insert.length) };\n        });\n    }\n    else if (byLine) {\n        changes = state.changeByRange(range => {\n            let line = text.line(i++);\n            return { changes: { from: range.from, to: range.to, insert: line.text },\n                range: _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.EditorSelection.cursor(range.from + line.length) };\n        });\n    }\n    else {\n        changes = state.replaceSelection(text);\n    }\n    view.dispatch(changes, {\n        userEvent: \"input.paste\",\n        scrollIntoView: true\n    });\n}\nobservers.scroll = view => {\n    view.inputState.lastScrollTop = view.scrollDOM.scrollTop;\n    view.inputState.lastScrollLeft = view.scrollDOM.scrollLeft;\n};\nhandlers.keydown = (view, event) => {\n    view.inputState.setSelectionOrigin(\"select\");\n    if (event.keyCode == 27 && view.inputState.tabFocusMode != 0)\n        view.inputState.tabFocusMode = Date.now() + 2000;\n    return false;\n};\nobservers.touchstart = (view, e) => {\n    view.inputState.lastTouchTime = Date.now();\n    view.inputState.setSelectionOrigin(\"select.pointer\");\n};\nobservers.touchmove = view => {\n    view.inputState.setSelectionOrigin(\"select.pointer\");\n};\nhandlers.mousedown = (view, event) => {\n    view.observer.flush();\n    if (view.inputState.lastTouchTime > Date.now() - 2000)\n        return false; // Ignore touch interaction\n    let style = null;\n    for (let makeStyle of view.state.facet(mouseSelectionStyle)) {\n        style = makeStyle(view, event);\n        if (style)\n            break;\n    }\n    if (!style && event.button == 0)\n        style = basicMouseSelection(view, event);\n    if (style) {\n        let mustFocus = !view.hasFocus;\n        view.inputState.startMouseSelection(new MouseSelection(view, event, style, mustFocus));\n        if (mustFocus)\n            view.observer.ignore(() => {\n                focusPreventScroll(view.contentDOM);\n                let active = view.root.activeElement;\n                if (active && !active.contains(view.contentDOM))\n                    active.blur();\n            });\n        let mouseSel = view.inputState.mouseSelection;\n        if (mouseSel) {\n            mouseSel.start(event);\n            return mouseSel.dragging === false;\n        }\n    }\n    return false;\n};\nfunction rangeForClick(view, pos, bias, type) {\n    if (type == 1) { // Single click\n        return _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.EditorSelection.cursor(pos, bias);\n    }\n    else if (type == 2) { // Double click\n        return groupAt(view.state, pos, bias);\n    }\n    else { // Triple click\n        let visual = LineView.find(view.docView, pos), line = view.state.doc.lineAt(visual ? visual.posAtEnd : pos);\n        let from = visual ? visual.posAtStart : line.from, to = visual ? visual.posAtEnd : line.to;\n        if (to < view.state.doc.length && to == line.to)\n            to++;\n        return _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.EditorSelection.range(from, to);\n    }\n}\nlet insideY = (y, rect) => y >= rect.top && y <= rect.bottom;\nlet inside = (x, y, rect) => insideY(y, rect) && x >= rect.left && x <= rect.right;\n// Try to determine, for the given coordinates, associated with the\n// given position, whether they are related to the element before or\n// the element after the position.\nfunction findPositionSide(view, pos, x, y) {\n    let line = LineView.find(view.docView, pos);\n    if (!line)\n        return 1;\n    let off = pos - line.posAtStart;\n    // Line boundaries point into the line\n    if (off == 0)\n        return 1;\n    if (off == line.length)\n        return -1;\n    // Positions on top of an element point at that element\n    let before = line.coordsAt(off, -1);\n    if (before && inside(x, y, before))\n        return -1;\n    let after = line.coordsAt(off, 1);\n    if (after && inside(x, y, after))\n        return 1;\n    // This is probably a line wrap point. Pick before if the point is\n    // beside it.\n    return before && insideY(y, before) ? -1 : 1;\n}\nfunction queryPos(view, event) {\n    let pos = view.posAtCoords({ x: event.clientX, y: event.clientY }, false);\n    return { pos, bias: findPositionSide(view, pos, event.clientX, event.clientY) };\n}\nconst BadMouseDetail = browser.ie && browser.ie_version <= 11;\nlet lastMouseDown = null, lastMouseDownCount = 0, lastMouseDownTime = 0;\nfunction getClickType(event) {\n    if (!BadMouseDetail)\n        return event.detail;\n    let last = lastMouseDown, lastTime = lastMouseDownTime;\n    lastMouseDown = event;\n    lastMouseDownTime = Date.now();\n    return lastMouseDownCount = !last || (lastTime > Date.now() - 400 && Math.abs(last.clientX - event.clientX) < 2 &&\n        Math.abs(last.clientY - event.clientY) < 2) ? (lastMouseDownCount + 1) % 3 : 1;\n}\nfunction basicMouseSelection(view, event) {\n    let start = queryPos(view, event), type = getClickType(event);\n    let startSel = view.state.selection;\n    return {\n        update(update) {\n            if (update.docChanged) {\n                start.pos = update.changes.mapPos(start.pos);\n                startSel = startSel.map(update.changes);\n            }\n        },\n        get(event, extend, multiple) {\n            let cur = queryPos(view, event), removed;\n            let range = rangeForClick(view, cur.pos, cur.bias, type);\n            if (start.pos != cur.pos && !extend) {\n                let startRange = rangeForClick(view, start.pos, start.bias, type);\n                let from = Math.min(startRange.from, range.from), to = Math.max(startRange.to, range.to);\n                range = from < range.from ? _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.EditorSelection.range(from, to) : _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.EditorSelection.range(to, from);\n            }\n            if (extend)\n                return startSel.replaceRange(startSel.main.extend(range.from, range.to));\n            else if (multiple && type == 1 && startSel.ranges.length > 1 && (removed = removeRangeAround(startSel, cur.pos)))\n                return removed;\n            else if (multiple)\n                return startSel.addRange(range);\n            else\n                return _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.EditorSelection.create([range]);\n        }\n    };\n}\nfunction removeRangeAround(sel, pos) {\n    for (let i = 0; i < sel.ranges.length; i++) {\n        let { from, to } = sel.ranges[i];\n        if (from <= pos && to >= pos)\n            return _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.EditorSelection.create(sel.ranges.slice(0, i).concat(sel.ranges.slice(i + 1)), sel.mainIndex == i ? 0 : sel.mainIndex - (sel.mainIndex > i ? 1 : 0));\n    }\n    return null;\n}\nhandlers.dragstart = (view, event) => {\n    let { selection: { main: range } } = view.state;\n    if (event.target.draggable) {\n        let cView = view.docView.nearest(event.target);\n        if (cView && cView.isWidget) {\n            let from = cView.posAtStart, to = from + cView.length;\n            if (from >= range.to || to <= range.from)\n                range = _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.EditorSelection.range(from, to);\n        }\n    }\n    let { inputState } = view;\n    if (inputState.mouseSelection)\n        inputState.mouseSelection.dragging = true;\n    inputState.draggedContent = range;\n    if (event.dataTransfer) {\n        event.dataTransfer.setData(\"Text\", view.state.sliceDoc(range.from, range.to));\n        event.dataTransfer.effectAllowed = \"copyMove\";\n    }\n    return false;\n};\nhandlers.dragend = view => {\n    view.inputState.draggedContent = null;\n    return false;\n};\nfunction dropText(view, event, text, direct) {\n    if (!text)\n        return;\n    let dropPos = view.posAtCoords({ x: event.clientX, y: event.clientY }, false);\n    let { draggedContent } = view.inputState;\n    let del = direct && draggedContent && dragMovesSelection(view, event)\n        ? { from: draggedContent.from, to: draggedContent.to } : null;\n    let ins = { from: dropPos, insert: text };\n    let changes = view.state.changes(del ? [del, ins] : ins);\n    view.focus();\n    view.dispatch({\n        changes,\n        selection: { anchor: changes.mapPos(dropPos, -1), head: changes.mapPos(dropPos, 1) },\n        userEvent: del ? \"move.drop\" : \"input.drop\"\n    });\n    view.inputState.draggedContent = null;\n}\nhandlers.drop = (view, event) => {\n    if (!event.dataTransfer)\n        return false;\n    if (view.state.readOnly)\n        return true;\n    let files = event.dataTransfer.files;\n    if (files && files.length) { // For a file drop, read the file's text.\n        let text = Array(files.length), read = 0;\n        let finishFile = () => {\n            if (++read == files.length)\n                dropText(view, event, text.filter(s => s != null).join(view.state.lineBreak), false);\n        };\n        for (let i = 0; i < files.length; i++) {\n            let reader = new FileReader;\n            reader.onerror = finishFile;\n            reader.onload = () => {\n                if (!/[\\x00-\\x08\\x0e-\\x1f]{2}/.test(reader.result))\n                    text[i] = reader.result;\n                finishFile();\n            };\n            reader.readAsText(files[i]);\n        }\n        return true;\n    }\n    else {\n        let text = event.dataTransfer.getData(\"Text\");\n        if (text) {\n            dropText(view, event, text, true);\n            return true;\n        }\n    }\n    return false;\n};\nhandlers.paste = (view, event) => {\n    if (view.state.readOnly)\n        return true;\n    view.observer.flush();\n    let data = brokenClipboardAPI ? null : event.clipboardData;\n    if (data) {\n        doPaste(view, data.getData(\"text/plain\") || data.getData(\"text/uri-list\"));\n        return true;\n    }\n    else {\n        capturePaste(view);\n        return false;\n    }\n};\nfunction captureCopy(view, text) {\n    // The extra wrapper is somehow necessary on IE/Edge to prevent the\n    // content from being mangled when it is put onto the clipboard\n    let parent = view.dom.parentNode;\n    if (!parent)\n        return;\n    let target = parent.appendChild(document.createElement(\"textarea\"));\n    target.style.cssText = \"position: fixed; left: -10000px; top: 10px\";\n    target.value = text;\n    target.focus();\n    target.selectionEnd = text.length;\n    target.selectionStart = 0;\n    setTimeout(() => {\n        target.remove();\n        view.focus();\n    }, 50);\n}\nfunction copiedRange(state) {\n    let content = [], ranges = [], linewise = false;\n    for (let range of state.selection.ranges)\n        if (!range.empty) {\n            content.push(state.sliceDoc(range.from, range.to));\n            ranges.push(range);\n        }\n    if (!content.length) {\n        // Nothing selected, do a line-wise copy\n        let upto = -1;\n        for (let { from } of state.selection.ranges) {\n            let line = state.doc.lineAt(from);\n            if (line.number > upto) {\n                content.push(line.text);\n                ranges.push({ from: line.from, to: Math.min(state.doc.length, line.to + 1) });\n            }\n            upto = line.number;\n        }\n        linewise = true;\n    }\n    return { text: content.join(state.lineBreak), ranges, linewise };\n}\nlet lastLinewiseCopy = null;\nhandlers.copy = handlers.cut = (view, event) => {\n    let { text, ranges, linewise } = copiedRange(view.state);\n    if (!text && !linewise)\n        return false;\n    lastLinewiseCopy = linewise ? text : null;\n    if (event.type == \"cut\" && !view.state.readOnly)\n        view.dispatch({\n            changes: ranges,\n            scrollIntoView: true,\n            userEvent: \"delete.cut\"\n        });\n    let data = brokenClipboardAPI ? null : event.clipboardData;\n    if (data) {\n        data.clearData();\n        data.setData(\"text/plain\", text);\n        return true;\n    }\n    else {\n        captureCopy(view, text);\n        return false;\n    }\n};\nconst isFocusChange = /*@__PURE__*/_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.Annotation.define();\nfunction focusChangeTransaction(state, focus) {\n    let effects = [];\n    for (let getEffect of state.facet(focusChangeEffect)) {\n        let effect = getEffect(state, focus);\n        if (effect)\n            effects.push(effect);\n    }\n    return effects ? state.update({ effects, annotations: isFocusChange.of(true) }) : null;\n}\nfunction updateForFocusChange(view) {\n    setTimeout(() => {\n        let focus = view.hasFocus;\n        if (focus != view.inputState.notifiedFocused) {\n            let tr = focusChangeTransaction(view.state, focus);\n            if (tr)\n                view.dispatch(tr);\n            else\n                view.update([]);\n        }\n    }, 10);\n}\nobservers.focus = view => {\n    view.inputState.lastFocusTime = Date.now();\n    // When focusing reset the scroll position, move it back to where it was\n    if (!view.scrollDOM.scrollTop && (view.inputState.lastScrollTop || view.inputState.lastScrollLeft)) {\n        view.scrollDOM.scrollTop = view.inputState.lastScrollTop;\n        view.scrollDOM.scrollLeft = view.inputState.lastScrollLeft;\n    }\n    updateForFocusChange(view);\n};\nobservers.blur = view => {\n    view.observer.clearSelectionRange();\n    updateForFocusChange(view);\n};\nobservers.compositionstart = observers.compositionupdate = view => {\n    if (view.observer.editContext)\n        return; // Composition handled by edit context\n    if (view.inputState.compositionFirstChange == null)\n        view.inputState.compositionFirstChange = true;\n    if (view.inputState.composing < 0) {\n        // FIXME possibly set a timeout to clear it again on Android\n        view.inputState.composing = 0;\n    }\n};\nobservers.compositionend = view => {\n    if (view.observer.editContext)\n        return; // Composition handled by edit context\n    view.inputState.composing = -1;\n    view.inputState.compositionEndedAt = Date.now();\n    view.inputState.compositionPendingKey = true;\n    view.inputState.compositionPendingChange = view.observer.pendingRecords().length > 0;\n    view.inputState.compositionFirstChange = null;\n    if (browser.chrome && browser.android) {\n        // Delay flushing for a bit on Android because it'll often fire a\n        // bunch of contradictory changes in a row at end of compositon\n        view.observer.flushSoon();\n    }\n    else if (view.inputState.compositionPendingChange) {\n        // If we found pending records, schedule a flush.\n        Promise.resolve().then(() => view.observer.flush());\n    }\n    else {\n        // Otherwise, make sure that, if no changes come in soon, the\n        // composition view is cleared.\n        setTimeout(() => {\n            if (view.inputState.composing < 0 && view.docView.hasComposition)\n                view.update([]);\n        }, 50);\n    }\n};\nobservers.contextmenu = view => {\n    view.inputState.lastContextMenu = Date.now();\n};\nhandlers.beforeinput = (view, event) => {\n    var _a;\n    // Because Chrome Android doesn't fire useful key events, use\n    // beforeinput to detect backspace (and possibly enter and delete,\n    // but those usually don't even seem to fire beforeinput events at\n    // the moment) and fake a key event for it.\n    //\n    // (preventDefault on beforeinput, though supported in the spec,\n    // seems to do nothing at all on Chrome).\n    let pending;\n    if (browser.chrome && browser.android && (pending = PendingKeys.find(key => key.inputType == event.inputType))) {\n        view.observer.delayAndroidKey(pending.key, pending.keyCode);\n        if (pending.key == \"Backspace\" || pending.key == \"Delete\") {\n            let startViewHeight = ((_a = window.visualViewport) === null || _a === void 0 ? void 0 : _a.height) || 0;\n            setTimeout(() => {\n                var _a;\n                // Backspacing near uneditable nodes on Chrome Android sometimes\n                // closes the virtual keyboard. This tries to crudely detect\n                // that and refocus to get it back.\n                if ((((_a = window.visualViewport) === null || _a === void 0 ? void 0 : _a.height) || 0) > startViewHeight + 10 && view.hasFocus) {\n                    view.contentDOM.blur();\n                    view.focus();\n                }\n            }, 100);\n        }\n    }\n    if (browser.ios && event.inputType == \"deleteContentForward\") {\n        // For some reason, DOM changes (and beforeinput) happen _before_\n        // the key event for ctrl-d on iOS when using an external\n        // keyboard.\n        view.observer.flushSoon();\n    }\n    // Safari will occasionally forget to fire compositionend at the end of a dead-key composition\n    if (browser.safari && event.inputType == \"insertText\" && view.inputState.composing >= 0) {\n        setTimeout(() => observers.compositionend(view, event), 20);\n    }\n    return false;\n};\nconst appliedFirefoxHack = /*@__PURE__*/new Set;\n// In Firefox, when cut/copy handlers are added to the document, that\n// somehow avoids a bug where those events aren't fired when the\n// selection is empty. See https://github.com/codemirror/dev/issues/1082\n// and https://bugzilla.mozilla.org/show_bug.cgi?id=995961\nfunction firefoxCopyCutHack(doc) {\n    if (!appliedFirefoxHack.has(doc)) {\n        appliedFirefoxHack.add(doc);\n        doc.addEventListener(\"copy\", () => { });\n        doc.addEventListener(\"cut\", () => { });\n    }\n}\n\nconst wrappingWhiteSpace = [\"pre-wrap\", \"normal\", \"pre-line\", \"break-spaces\"];\nclass HeightOracle {\n    constructor(lineWrapping) {\n        this.lineWrapping = lineWrapping;\n        this.doc = _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.Text.empty;\n        this.heightSamples = {};\n        this.lineHeight = 14; // The height of an entire line (line-height)\n        this.charWidth = 7;\n        this.textHeight = 14; // The height of the actual font (font-size)\n        this.lineLength = 30;\n        // Used to track, during updateHeight, if any actual heights changed\n        this.heightChanged = false;\n    }\n    heightForGap(from, to) {\n        let lines = this.doc.lineAt(to).number - this.doc.lineAt(from).number + 1;\n        if (this.lineWrapping)\n            lines += Math.max(0, Math.ceil(((to - from) - (lines * this.lineLength * 0.5)) / this.lineLength));\n        return this.lineHeight * lines;\n    }\n    heightForLine(length) {\n        if (!this.lineWrapping)\n            return this.lineHeight;\n        let lines = 1 + Math.max(0, Math.ceil((length - this.lineLength) / (this.lineLength - 5)));\n        return lines * this.lineHeight;\n    }\n    setDoc(doc) { this.doc = doc; return this; }\n    mustRefreshForWrapping(whiteSpace) {\n        return (wrappingWhiteSpace.indexOf(whiteSpace) > -1) != this.lineWrapping;\n    }\n    mustRefreshForHeights(lineHeights) {\n        let newHeight = false;\n        for (let i = 0; i < lineHeights.length; i++) {\n            let h = lineHeights[i];\n            if (h < 0) {\n                i++;\n            }\n            else if (!this.heightSamples[Math.floor(h * 10)]) { // Round to .1 pixels\n                newHeight = true;\n                this.heightSamples[Math.floor(h * 10)] = true;\n            }\n        }\n        return newHeight;\n    }\n    refresh(whiteSpace, lineHeight, charWidth, textHeight, lineLength, knownHeights) {\n        let lineWrapping = wrappingWhiteSpace.indexOf(whiteSpace) > -1;\n        let changed = Math.round(lineHeight) != Math.round(this.lineHeight) || this.lineWrapping != lineWrapping;\n        this.lineWrapping = lineWrapping;\n        this.lineHeight = lineHeight;\n        this.charWidth = charWidth;\n        this.textHeight = textHeight;\n        this.lineLength = lineLength;\n        if (changed) {\n            this.heightSamples = {};\n            for (let i = 0; i < knownHeights.length; i++) {\n                let h = knownHeights[i];\n                if (h < 0)\n                    i++;\n                else\n                    this.heightSamples[Math.floor(h * 10)] = true;\n            }\n        }\n        return changed;\n    }\n}\n// This object is used by `updateHeight` to make DOM measurements\n// arrive at the right nides. The `heights` array is a sequence of\n// block heights, starting from position `from`.\nclass MeasuredHeights {\n    constructor(from, heights) {\n        this.from = from;\n        this.heights = heights;\n        this.index = 0;\n    }\n    get more() { return this.index < this.heights.length; }\n}\n/**\nRecord used to represent information about a block-level element\nin the editor view.\n*/\nclass BlockInfo {\n    /**\n    @internal\n    */\n    constructor(\n    /**\n    The start of the element in the document.\n    */\n    from, \n    /**\n    The length of the element.\n    */\n    length, \n    /**\n    The top position of the element (relative to the top of the\n    document).\n    */\n    top, \n    /**\n    Its height.\n    */\n    height, \n    /**\n    @internal Weird packed field that holds an array of children\n    for composite blocks, a decoration for block widgets, and a\n    number indicating the amount of widget-create line breaks for\n    text blocks.\n    */\n    _content) {\n        this.from = from;\n        this.length = length;\n        this.top = top;\n        this.height = height;\n        this._content = _content;\n    }\n    /**\n    The type of element this is. When querying lines, this may be\n    an array of all the blocks that make up the line.\n    */\n    get type() {\n        return typeof this._content == \"number\" ? BlockType.Text :\n            Array.isArray(this._content) ? this._content : this._content.type;\n    }\n    /**\n    The end of the element as a document position.\n    */\n    get to() { return this.from + this.length; }\n    /**\n    The bottom position of the element.\n    */\n    get bottom() { return this.top + this.height; }\n    /**\n    If this is a widget block, this will return the widget\n    associated with it.\n    */\n    get widget() {\n        return this._content instanceof PointDecoration ? this._content.widget : null;\n    }\n    /**\n    If this is a textblock, this holds the number of line breaks\n    that appear in widgets inside the block.\n    */\n    get widgetLineBreaks() {\n        return typeof this._content == \"number\" ? this._content : 0;\n    }\n    /**\n    @internal\n    */\n    join(other) {\n        let content = (Array.isArray(this._content) ? this._content : [this])\n            .concat(Array.isArray(other._content) ? other._content : [other]);\n        return new BlockInfo(this.from, this.length + other.length, this.top, this.height + other.height, content);\n    }\n}\nvar QueryType = /*@__PURE__*/(function (QueryType) {\n    QueryType[QueryType[\"ByPos\"] = 0] = \"ByPos\";\n    QueryType[QueryType[\"ByHeight\"] = 1] = \"ByHeight\";\n    QueryType[QueryType[\"ByPosNoHeight\"] = 2] = \"ByPosNoHeight\";\nreturn QueryType})(QueryType || (QueryType = {}));\nconst Epsilon = 1e-3;\nclass HeightMap {\n    constructor(length, // The number of characters covered\n    height, // Height of this part of the document\n    flags = 2 /* Flag.Outdated */) {\n        this.length = length;\n        this.height = height;\n        this.flags = flags;\n    }\n    get outdated() { return (this.flags & 2 /* Flag.Outdated */) > 0; }\n    set outdated(value) { this.flags = (value ? 2 /* Flag.Outdated */ : 0) | (this.flags & ~2 /* Flag.Outdated */); }\n    setHeight(oracle, height) {\n        if (this.height != height) {\n            if (Math.abs(this.height - height) > Epsilon)\n                oracle.heightChanged = true;\n            this.height = height;\n        }\n    }\n    // Base case is to replace a leaf node, which simply builds a tree\n    // from the new nodes and returns that (HeightMapBranch and\n    // HeightMapGap override this to actually use from/to)\n    replace(_from, _to, nodes) {\n        return HeightMap.of(nodes);\n    }\n    // Again, these are base cases, and are overridden for branch and gap nodes.\n    decomposeLeft(_to, result) { result.push(this); }\n    decomposeRight(_from, result) { result.push(this); }\n    applyChanges(decorations, oldDoc, oracle, changes) {\n        let me = this, doc = oracle.doc;\n        for (let i = changes.length - 1; i >= 0; i--) {\n            let { fromA, toA, fromB, toB } = changes[i];\n            let start = me.lineAt(fromA, QueryType.ByPosNoHeight, oracle.setDoc(oldDoc), 0, 0);\n            let end = start.to >= toA ? start : me.lineAt(toA, QueryType.ByPosNoHeight, oracle, 0, 0);\n            toB += end.to - toA;\n            toA = end.to;\n            while (i > 0 && start.from <= changes[i - 1].toA) {\n                fromA = changes[i - 1].fromA;\n                fromB = changes[i - 1].fromB;\n                i--;\n                if (fromA < start.from)\n                    start = me.lineAt(fromA, QueryType.ByPosNoHeight, oracle, 0, 0);\n            }\n            fromB += start.from - fromA;\n            fromA = start.from;\n            let nodes = NodeBuilder.build(oracle.setDoc(doc), decorations, fromB, toB);\n            me = me.replace(fromA, toA, nodes);\n        }\n        return me.updateHeight(oracle, 0);\n    }\n    static empty() { return new HeightMapText(0, 0); }\n    // nodes uses null values to indicate the position of line breaks.\n    // There are never line breaks at the start or end of the array, or\n    // two line breaks next to each other, and the array isn't allowed\n    // to be empty (same restrictions as return value from the builder).\n    static of(nodes) {\n        if (nodes.length == 1)\n            return nodes[0];\n        let i = 0, j = nodes.length, before = 0, after = 0;\n        for (;;) {\n            if (i == j) {\n                if (before > after * 2) {\n                    let split = nodes[i - 1];\n                    if (split.break)\n                        nodes.splice(--i, 1, split.left, null, split.right);\n                    else\n                        nodes.splice(--i, 1, split.left, split.right);\n                    j += 1 + split.break;\n                    before -= split.size;\n                }\n                else if (after > before * 2) {\n                    let split = nodes[j];\n                    if (split.break)\n                        nodes.splice(j, 1, split.left, null, split.right);\n                    else\n                        nodes.splice(j, 1, split.left, split.right);\n                    j += 2 + split.break;\n                    after -= split.size;\n                }\n                else {\n                    break;\n                }\n            }\n            else if (before < after) {\n                let next = nodes[i++];\n                if (next)\n                    before += next.size;\n            }\n            else {\n                let next = nodes[--j];\n                if (next)\n                    after += next.size;\n            }\n        }\n        let brk = 0;\n        if (nodes[i - 1] == null) {\n            brk = 1;\n            i--;\n        }\n        else if (nodes[i] == null) {\n            brk = 1;\n            j++;\n        }\n        return new HeightMapBranch(HeightMap.of(nodes.slice(0, i)), brk, HeightMap.of(nodes.slice(j)));\n    }\n}\nHeightMap.prototype.size = 1;\nclass HeightMapBlock extends HeightMap {\n    constructor(length, height, deco) {\n        super(length, height);\n        this.deco = deco;\n    }\n    blockAt(_height, _oracle, top, offset) {\n        return new BlockInfo(offset, this.length, top, this.height, this.deco || 0);\n    }\n    lineAt(_value, _type, oracle, top, offset) {\n        return this.blockAt(0, oracle, top, offset);\n    }\n    forEachLine(from, to, oracle, top, offset, f) {\n        if (from <= offset + this.length && to >= offset)\n            f(this.blockAt(0, oracle, top, offset));\n    }\n    updateHeight(oracle, offset = 0, _force = false, measured) {\n        if (measured && measured.from <= offset && measured.more)\n            this.setHeight(oracle, measured.heights[measured.index++]);\n        this.outdated = false;\n        return this;\n    }\n    toString() { return `block(${this.length})`; }\n}\nclass HeightMapText extends HeightMapBlock {\n    constructor(length, height) {\n        super(length, height, null);\n        this.collapsed = 0; // Amount of collapsed content in the line\n        this.widgetHeight = 0; // Maximum inline widget height\n        this.breaks = 0; // Number of widget-introduced line breaks on the line\n    }\n    blockAt(_height, _oracle, top, offset) {\n        return new BlockInfo(offset, this.length, top, this.height, this.breaks);\n    }\n    replace(_from, _to, nodes) {\n        let node = nodes[0];\n        if (nodes.length == 1 && (node instanceof HeightMapText || node instanceof HeightMapGap && (node.flags & 4 /* Flag.SingleLine */)) &&\n            Math.abs(this.length - node.length) < 10) {\n            if (node instanceof HeightMapGap)\n                node = new HeightMapText(node.length, this.height);\n            else\n                node.height = this.height;\n            if (!this.outdated)\n                node.outdated = false;\n            return node;\n        }\n        else {\n            return HeightMap.of(nodes);\n        }\n    }\n    updateHeight(oracle, offset = 0, force = false, measured) {\n        if (measured && measured.from <= offset && measured.more)\n            this.setHeight(oracle, measured.heights[measured.index++]);\n        else if (force || this.outdated)\n            this.setHeight(oracle, Math.max(this.widgetHeight, oracle.heightForLine(this.length - this.collapsed)) +\n                this.breaks * oracle.lineHeight);\n        this.outdated = false;\n        return this;\n    }\n    toString() {\n        return `line(${this.length}${this.collapsed ? -this.collapsed : \"\"}${this.widgetHeight ? \":\" + this.widgetHeight : \"\"})`;\n    }\n}\nclass HeightMapGap extends HeightMap {\n    constructor(length) { super(length, 0); }\n    heightMetrics(oracle, offset) {\n        let firstLine = oracle.doc.lineAt(offset).number, lastLine = oracle.doc.lineAt(offset + this.length).number;\n        let lines = lastLine - firstLine + 1;\n        let perLine, perChar = 0;\n        if (oracle.lineWrapping) {\n            let totalPerLine = Math.min(this.height, oracle.lineHeight * lines);\n            perLine = totalPerLine / lines;\n            if (this.length > lines + 1)\n                perChar = (this.height - totalPerLine) / (this.length - lines - 1);\n        }\n        else {\n            perLine = this.height / lines;\n        }\n        return { firstLine, lastLine, perLine, perChar };\n    }\n    blockAt(height, oracle, top, offset) {\n        let { firstLine, lastLine, perLine, perChar } = this.heightMetrics(oracle, offset);\n        if (oracle.lineWrapping) {\n            let guess = offset + (height < oracle.lineHeight ? 0\n                : Math.round(Math.max(0, Math.min(1, (height - top) / this.height)) * this.length));\n            let line = oracle.doc.lineAt(guess), lineHeight = perLine + line.length * perChar;\n            let lineTop = Math.max(top, height - lineHeight / 2);\n            return new BlockInfo(line.from, line.length, lineTop, lineHeight, 0);\n        }\n        else {\n            let line = Math.max(0, Math.min(lastLine - firstLine, Math.floor((height - top) / perLine)));\n            let { from, length } = oracle.doc.line(firstLine + line);\n            return new BlockInfo(from, length, top + perLine * line, perLine, 0);\n        }\n    }\n    lineAt(value, type, oracle, top, offset) {\n        if (type == QueryType.ByHeight)\n            return this.blockAt(value, oracle, top, offset);\n        if (type == QueryType.ByPosNoHeight) {\n            let { from, to } = oracle.doc.lineAt(value);\n            return new BlockInfo(from, to - from, 0, 0, 0);\n        }\n        let { firstLine, perLine, perChar } = this.heightMetrics(oracle, offset);\n        let line = oracle.doc.lineAt(value), lineHeight = perLine + line.length * perChar;\n        let linesAbove = line.number - firstLine;\n        let lineTop = top + perLine * linesAbove + perChar * (line.from - offset - linesAbove);\n        return new BlockInfo(line.from, line.length, Math.max(top, Math.min(lineTop, top + this.height - lineHeight)), lineHeight, 0);\n    }\n    forEachLine(from, to, oracle, top, offset, f) {\n        from = Math.max(from, offset);\n        to = Math.min(to, offset + this.length);\n        let { firstLine, perLine, perChar } = this.heightMetrics(oracle, offset);\n        for (let pos = from, lineTop = top; pos <= to;) {\n            let line = oracle.doc.lineAt(pos);\n            if (pos == from) {\n                let linesAbove = line.number - firstLine;\n                lineTop += perLine * linesAbove + perChar * (from - offset - linesAbove);\n            }\n            let lineHeight = perLine + perChar * line.length;\n            f(new BlockInfo(line.from, line.length, lineTop, lineHeight, 0));\n            lineTop += lineHeight;\n            pos = line.to + 1;\n        }\n    }\n    replace(from, to, nodes) {\n        let after = this.length - to;\n        if (after > 0) {\n            let last = nodes[nodes.length - 1];\n            if (last instanceof HeightMapGap)\n                nodes[nodes.length - 1] = new HeightMapGap(last.length + after);\n            else\n                nodes.push(null, new HeightMapGap(after - 1));\n        }\n        if (from > 0) {\n            let first = nodes[0];\n            if (first instanceof HeightMapGap)\n                nodes[0] = new HeightMapGap(from + first.length);\n            else\n                nodes.unshift(new HeightMapGap(from - 1), null);\n        }\n        return HeightMap.of(nodes);\n    }\n    decomposeLeft(to, result) {\n        result.push(new HeightMapGap(to - 1), null);\n    }\n    decomposeRight(from, result) {\n        result.push(null, new HeightMapGap(this.length - from - 1));\n    }\n    updateHeight(oracle, offset = 0, force = false, measured) {\n        let end = offset + this.length;\n        if (measured && measured.from <= offset + this.length && measured.more) {\n            // Fill in part of this gap with measured lines. We know there\n            // can't be widgets or collapsed ranges in those lines, because\n            // they would already have been added to the heightmap (gaps\n            // only contain plain text).\n            let nodes = [], pos = Math.max(offset, measured.from), singleHeight = -1;\n            if (measured.from > offset)\n                nodes.push(new HeightMapGap(measured.from - offset - 1).updateHeight(oracle, offset));\n            while (pos <= end && measured.more) {\n                let len = oracle.doc.lineAt(pos).length;\n                if (nodes.length)\n                    nodes.push(null);\n                let height = measured.heights[measured.index++];\n                if (singleHeight == -1)\n                    singleHeight = height;\n                else if (Math.abs(height - singleHeight) >= Epsilon)\n                    singleHeight = -2;\n                let line = new HeightMapText(len, height);\n                line.outdated = false;\n                nodes.push(line);\n                pos += len + 1;\n            }\n            if (pos <= end)\n                nodes.push(null, new HeightMapGap(end - pos).updateHeight(oracle, pos));\n            let result = HeightMap.of(nodes);\n            if (singleHeight < 0 || Math.abs(result.height - this.height) >= Epsilon ||\n                Math.abs(singleHeight - this.heightMetrics(oracle, offset).perLine) >= Epsilon)\n                oracle.heightChanged = true;\n            return result;\n        }\n        else if (force || this.outdated) {\n            this.setHeight(oracle, oracle.heightForGap(offset, offset + this.length));\n            this.outdated = false;\n        }\n        return this;\n    }\n    toString() { return `gap(${this.length})`; }\n}\nclass HeightMapBranch extends HeightMap {\n    constructor(left, brk, right) {\n        super(left.length + brk + right.length, left.height + right.height, brk | (left.outdated || right.outdated ? 2 /* Flag.Outdated */ : 0));\n        this.left = left;\n        this.right = right;\n        this.size = left.size + right.size;\n    }\n    get break() { return this.flags & 1 /* Flag.Break */; }\n    blockAt(height, oracle, top, offset) {\n        let mid = top + this.left.height;\n        return height < mid ? this.left.blockAt(height, oracle, top, offset)\n            : this.right.blockAt(height, oracle, mid, offset + this.left.length + this.break);\n    }\n    lineAt(value, type, oracle, top, offset) {\n        let rightTop = top + this.left.height, rightOffset = offset + this.left.length + this.break;\n        let left = type == QueryType.ByHeight ? value < rightTop : value < rightOffset;\n        let base = left ? this.left.lineAt(value, type, oracle, top, offset)\n            : this.right.lineAt(value, type, oracle, rightTop, rightOffset);\n        if (this.break || (left ? base.to < rightOffset : base.from > rightOffset))\n            return base;\n        let subQuery = type == QueryType.ByPosNoHeight ? QueryType.ByPosNoHeight : QueryType.ByPos;\n        if (left)\n            return base.join(this.right.lineAt(rightOffset, subQuery, oracle, rightTop, rightOffset));\n        else\n            return this.left.lineAt(rightOffset, subQuery, oracle, top, offset).join(base);\n    }\n    forEachLine(from, to, oracle, top, offset, f) {\n        let rightTop = top + this.left.height, rightOffset = offset + this.left.length + this.break;\n        if (this.break) {\n            if (from < rightOffset)\n                this.left.forEachLine(from, to, oracle, top, offset, f);\n            if (to >= rightOffset)\n                this.right.forEachLine(from, to, oracle, rightTop, rightOffset, f);\n        }\n        else {\n            let mid = this.lineAt(rightOffset, QueryType.ByPos, oracle, top, offset);\n            if (from < mid.from)\n                this.left.forEachLine(from, mid.from - 1, oracle, top, offset, f);\n            if (mid.to >= from && mid.from <= to)\n                f(mid);\n            if (to > mid.to)\n                this.right.forEachLine(mid.to + 1, to, oracle, rightTop, rightOffset, f);\n        }\n    }\n    replace(from, to, nodes) {\n        let rightStart = this.left.length + this.break;\n        if (to < rightStart)\n            return this.balanced(this.left.replace(from, to, nodes), this.right);\n        if (from > this.left.length)\n            return this.balanced(this.left, this.right.replace(from - rightStart, to - rightStart, nodes));\n        let result = [];\n        if (from > 0)\n            this.decomposeLeft(from, result);\n        let left = result.length;\n        for (let node of nodes)\n            result.push(node);\n        if (from > 0)\n            mergeGaps(result, left - 1);\n        if (to < this.length) {\n            let right = result.length;\n            this.decomposeRight(to, result);\n            mergeGaps(result, right);\n        }\n        return HeightMap.of(result);\n    }\n    decomposeLeft(to, result) {\n        let left = this.left.length;\n        if (to <= left)\n            return this.left.decomposeLeft(to, result);\n        result.push(this.left);\n        if (this.break) {\n            left++;\n            if (to >= left)\n                result.push(null);\n        }\n        if (to > left)\n            this.right.decomposeLeft(to - left, result);\n    }\n    decomposeRight(from, result) {\n        let left = this.left.length, right = left + this.break;\n        if (from >= right)\n            return this.right.decomposeRight(from - right, result);\n        if (from < left)\n            this.left.decomposeRight(from, result);\n        if (this.break && from < right)\n            result.push(null);\n        result.push(this.right);\n    }\n    balanced(left, right) {\n        if (left.size > 2 * right.size || right.size > 2 * left.size)\n            return HeightMap.of(this.break ? [left, null, right] : [left, right]);\n        this.left = left;\n        this.right = right;\n        this.height = left.height + right.height;\n        this.outdated = left.outdated || right.outdated;\n        this.size = left.size + right.size;\n        this.length = left.length + this.break + right.length;\n        return this;\n    }\n    updateHeight(oracle, offset = 0, force = false, measured) {\n        let { left, right } = this, rightStart = offset + left.length + this.break, rebalance = null;\n        if (measured && measured.from <= offset + left.length && measured.more)\n            rebalance = left = left.updateHeight(oracle, offset, force, measured);\n        else\n            left.updateHeight(oracle, offset, force);\n        if (measured && measured.from <= rightStart + right.length && measured.more)\n            rebalance = right = right.updateHeight(oracle, rightStart, force, measured);\n        else\n            right.updateHeight(oracle, rightStart, force);\n        if (rebalance)\n            return this.balanced(left, right);\n        this.height = this.left.height + this.right.height;\n        this.outdated = false;\n        return this;\n    }\n    toString() { return this.left + (this.break ? \" \" : \"-\") + this.right; }\n}\nfunction mergeGaps(nodes, around) {\n    let before, after;\n    if (nodes[around] == null &&\n        (before = nodes[around - 1]) instanceof HeightMapGap &&\n        (after = nodes[around + 1]) instanceof HeightMapGap)\n        nodes.splice(around - 1, 3, new HeightMapGap(before.length + 1 + after.length));\n}\nconst relevantWidgetHeight = 5;\nclass NodeBuilder {\n    constructor(pos, oracle) {\n        this.pos = pos;\n        this.oracle = oracle;\n        this.nodes = [];\n        this.lineStart = -1;\n        this.lineEnd = -1;\n        this.covering = null;\n        this.writtenTo = pos;\n    }\n    get isCovered() {\n        return this.covering && this.nodes[this.nodes.length - 1] == this.covering;\n    }\n    span(_from, to) {\n        if (this.lineStart > -1) {\n            let end = Math.min(to, this.lineEnd), last = this.nodes[this.nodes.length - 1];\n            if (last instanceof HeightMapText)\n                last.length += end - this.pos;\n            else if (end > this.pos || !this.isCovered)\n                this.nodes.push(new HeightMapText(end - this.pos, -1));\n            this.writtenTo = end;\n            if (to > end) {\n                this.nodes.push(null);\n                this.writtenTo++;\n                this.lineStart = -1;\n            }\n        }\n        this.pos = to;\n    }\n    point(from, to, deco) {\n        if (from < to || deco.heightRelevant) {\n            let height = deco.widget ? deco.widget.estimatedHeight : 0;\n            let breaks = deco.widget ? deco.widget.lineBreaks : 0;\n            if (height < 0)\n                height = this.oracle.lineHeight;\n            let len = to - from;\n            if (deco.block) {\n                this.addBlock(new HeightMapBlock(len, height, deco));\n            }\n            else if (len || breaks || height >= relevantWidgetHeight) {\n                this.addLineDeco(height, breaks, len);\n            }\n        }\n        else if (to > from) {\n            this.span(from, to);\n        }\n        if (this.lineEnd > -1 && this.lineEnd < this.pos)\n            this.lineEnd = this.oracle.doc.lineAt(this.pos).to;\n    }\n    enterLine() {\n        if (this.lineStart > -1)\n            return;\n        let { from, to } = this.oracle.doc.lineAt(this.pos);\n        this.lineStart = from;\n        this.lineEnd = to;\n        if (this.writtenTo < from) {\n            if (this.writtenTo < from - 1 || this.nodes[this.nodes.length - 1] == null)\n                this.nodes.push(this.blankContent(this.writtenTo, from - 1));\n            this.nodes.push(null);\n        }\n        if (this.pos > from)\n            this.nodes.push(new HeightMapText(this.pos - from, -1));\n        this.writtenTo = this.pos;\n    }\n    blankContent(from, to) {\n        let gap = new HeightMapGap(to - from);\n        if (this.oracle.doc.lineAt(from).to == to)\n            gap.flags |= 4 /* Flag.SingleLine */;\n        return gap;\n    }\n    ensureLine() {\n        this.enterLine();\n        let last = this.nodes.length ? this.nodes[this.nodes.length - 1] : null;\n        if (last instanceof HeightMapText)\n            return last;\n        let line = new HeightMapText(0, -1);\n        this.nodes.push(line);\n        return line;\n    }\n    addBlock(block) {\n        this.enterLine();\n        let deco = block.deco;\n        if (deco && deco.startSide > 0 && !this.isCovered)\n            this.ensureLine();\n        this.nodes.push(block);\n        this.writtenTo = this.pos = this.pos + block.length;\n        if (deco && deco.endSide > 0)\n            this.covering = block;\n    }\n    addLineDeco(height, breaks, length) {\n        let line = this.ensureLine();\n        line.length += length;\n        line.collapsed += length;\n        line.widgetHeight = Math.max(line.widgetHeight, height);\n        line.breaks += breaks;\n        this.writtenTo = this.pos = this.pos + length;\n    }\n    finish(from) {\n        let last = this.nodes.length == 0 ? null : this.nodes[this.nodes.length - 1];\n        if (this.lineStart > -1 && !(last instanceof HeightMapText) && !this.isCovered)\n            this.nodes.push(new HeightMapText(0, -1));\n        else if (this.writtenTo < this.pos || last == null)\n            this.nodes.push(this.blankContent(this.writtenTo, this.pos));\n        let pos = from;\n        for (let node of this.nodes) {\n            if (node instanceof HeightMapText)\n                node.updateHeight(this.oracle, pos);\n            pos += node ? node.length : 1;\n        }\n        return this.nodes;\n    }\n    // Always called with a region that on both sides either stretches\n    // to a line break or the end of the document.\n    // The returned array uses null to indicate line breaks, but never\n    // starts or ends in a line break, or has multiple line breaks next\n    // to each other.\n    static build(oracle, decorations, from, to) {\n        let builder = new NodeBuilder(from, oracle);\n        _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.RangeSet.spans(decorations, from, to, builder, 0);\n        return builder.finish(from);\n    }\n}\nfunction heightRelevantDecoChanges(a, b, diff) {\n    let comp = new DecorationComparator;\n    _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.RangeSet.compare(a, b, diff, comp, 0);\n    return comp.changes;\n}\nclass DecorationComparator {\n    constructor() {\n        this.changes = [];\n    }\n    compareRange() { }\n    comparePoint(from, to, a, b) {\n        if (from < to || a && a.heightRelevant || b && b.heightRelevant)\n            addRange(from, to, this.changes, 5);\n    }\n}\n\nfunction visiblePixelRange(dom, paddingTop) {\n    let rect = dom.getBoundingClientRect();\n    let doc = dom.ownerDocument, win = doc.defaultView || window;\n    let left = Math.max(0, rect.left), right = Math.min(win.innerWidth, rect.right);\n    let top = Math.max(0, rect.top), bottom = Math.min(win.innerHeight, rect.bottom);\n    for (let parent = dom.parentNode; parent && parent != doc.body;) {\n        if (parent.nodeType == 1) {\n            let elt = parent;\n            let style = window.getComputedStyle(elt);\n            if ((elt.scrollHeight > elt.clientHeight || elt.scrollWidth > elt.clientWidth) &&\n                style.overflow != \"visible\") {\n                let parentRect = elt.getBoundingClientRect();\n                left = Math.max(left, parentRect.left);\n                right = Math.min(right, parentRect.right);\n                top = Math.max(top, parentRect.top);\n                bottom = parent == dom.parentNode ? parentRect.bottom : Math.min(bottom, parentRect.bottom);\n            }\n            parent = style.position == \"absolute\" || style.position == \"fixed\" ? elt.offsetParent : elt.parentNode;\n        }\n        else if (parent.nodeType == 11) { // Shadow root\n            parent = parent.host;\n        }\n        else {\n            break;\n        }\n    }\n    return { left: left - rect.left, right: Math.max(left, right) - rect.left,\n        top: top - (rect.top + paddingTop), bottom: Math.max(top, bottom) - (rect.top + paddingTop) };\n}\nfunction fullPixelRange(dom, paddingTop) {\n    let rect = dom.getBoundingClientRect();\n    return { left: 0, right: rect.right - rect.left,\n        top: paddingTop, bottom: rect.bottom - (rect.top + paddingTop) };\n}\n// Line gaps are placeholder widgets used to hide pieces of overlong\n// lines within the viewport, as a kludge to keep the editor\n// responsive when a ridiculously long line is loaded into it.\nclass LineGap {\n    constructor(from, to, size) {\n        this.from = from;\n        this.to = to;\n        this.size = size;\n    }\n    static same(a, b) {\n        if (a.length != b.length)\n            return false;\n        for (let i = 0; i < a.length; i++) {\n            let gA = a[i], gB = b[i];\n            if (gA.from != gB.from || gA.to != gB.to || gA.size != gB.size)\n                return false;\n        }\n        return true;\n    }\n    draw(viewState, wrapping) {\n        return Decoration.replace({\n            widget: new LineGapWidget(this.size * (wrapping ? viewState.scaleY : viewState.scaleX), wrapping)\n        }).range(this.from, this.to);\n    }\n}\nclass LineGapWidget extends WidgetType {\n    constructor(size, vertical) {\n        super();\n        this.size = size;\n        this.vertical = vertical;\n    }\n    eq(other) { return other.size == this.size && other.vertical == this.vertical; }\n    toDOM() {\n        let elt = document.createElement(\"div\");\n        if (this.vertical) {\n            elt.style.height = this.size + \"px\";\n        }\n        else {\n            elt.style.width = this.size + \"px\";\n            elt.style.height = \"2px\";\n            elt.style.display = \"inline-block\";\n        }\n        return elt;\n    }\n    get estimatedHeight() { return this.vertical ? this.size : -1; }\n}\nclass ViewState {\n    constructor(state) {\n        this.state = state;\n        // These are contentDOM-local coordinates\n        this.pixelViewport = { left: 0, right: window.innerWidth, top: 0, bottom: 0 };\n        this.inView = true;\n        this.paddingTop = 0; // Padding above the document, scaled\n        this.paddingBottom = 0; // Padding below the document, scaled\n        this.contentDOMWidth = 0; // contentDOM.getBoundingClientRect().width\n        this.contentDOMHeight = 0; // contentDOM.getBoundingClientRect().height\n        this.editorHeight = 0; // scrollDOM.clientHeight, unscaled\n        this.editorWidth = 0; // scrollDOM.clientWidth, unscaled\n        this.scrollTop = 0; // Last seen scrollDOM.scrollTop, scaled\n        this.scrolledToBottom = false;\n        // The CSS-transformation scale of the editor (transformed size /\n        // concrete size)\n        this.scaleX = 1;\n        this.scaleY = 1;\n        // The vertical position (document-relative) to which to anchor the\n        // scroll position. -1 means anchor to the end of the document.\n        this.scrollAnchorPos = 0;\n        // The height at the anchor position. Set by the DOM update phase.\n        // -1 means no height available.\n        this.scrollAnchorHeight = -1;\n        // See VP.MaxDOMHeight\n        this.scaler = IdScaler;\n        this.scrollTarget = null;\n        // Briefly set to true when printing, to disable viewport limiting\n        this.printing = false;\n        // Flag set when editor content was redrawn, so that the next\n        // measure stage knows it must read DOM layout\n        this.mustMeasureContent = true;\n        this.defaultTextDirection = Direction.LTR;\n        this.visibleRanges = [];\n        // Cursor 'assoc' is only significant when the cursor is on a line\n        // wrap point, where it must stick to the character that it is\n        // associated with. Since browsers don't provide a reasonable\n        // interface to set or query this, when a selection is set that\n        // might cause this to be significant, this flag is set. The next\n        // measure phase will check whether the cursor is on a line-wrapping\n        // boundary and, if so, reset it to make sure it is positioned in\n        // the right place.\n        this.mustEnforceCursorAssoc = false;\n        let guessWrapping = state.facet(contentAttributes).some(v => typeof v != \"function\" && v.class == \"cm-lineWrapping\");\n        this.heightOracle = new HeightOracle(guessWrapping);\n        this.stateDeco = state.facet(decorations).filter(d => typeof d != \"function\");\n        this.heightMap = HeightMap.empty().applyChanges(this.stateDeco, _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.Text.empty, this.heightOracle.setDoc(state.doc), [new ChangedRange(0, 0, 0, state.doc.length)]);\n        for (let i = 0; i < 2; i++) {\n            this.viewport = this.getViewport(0, null);\n            if (!this.updateForViewport())\n                break;\n        }\n        this.updateViewportLines();\n        this.lineGaps = this.ensureLineGaps([]);\n        this.lineGapDeco = Decoration.set(this.lineGaps.map(gap => gap.draw(this, false)));\n        this.computeVisibleRanges();\n    }\n    updateForViewport() {\n        let viewports = [this.viewport], { main } = this.state.selection;\n        for (let i = 0; i <= 1; i++) {\n            let pos = i ? main.head : main.anchor;\n            if (!viewports.some(({ from, to }) => pos >= from && pos <= to)) {\n                let { from, to } = this.lineBlockAt(pos);\n                viewports.push(new Viewport(from, to));\n            }\n        }\n        this.viewports = viewports.sort((a, b) => a.from - b.from);\n        return this.updateScaler();\n    }\n    updateScaler() {\n        let scaler = this.scaler;\n        this.scaler = this.heightMap.height <= 7000000 /* VP.MaxDOMHeight */ ? IdScaler :\n            new BigScaler(this.heightOracle, this.heightMap, this.viewports);\n        return scaler.eq(this.scaler) ? 0 : 2 /* UpdateFlag.Height */;\n    }\n    updateViewportLines() {\n        this.viewportLines = [];\n        this.heightMap.forEachLine(this.viewport.from, this.viewport.to, this.heightOracle.setDoc(this.state.doc), 0, 0, block => {\n            this.viewportLines.push(scaleBlock(block, this.scaler));\n        });\n    }\n    update(update, scrollTarget = null) {\n        this.state = update.state;\n        let prevDeco = this.stateDeco;\n        this.stateDeco = this.state.facet(decorations).filter(d => typeof d != \"function\");\n        let contentChanges = update.changedRanges;\n        let heightChanges = ChangedRange.extendWithRanges(contentChanges, heightRelevantDecoChanges(prevDeco, this.stateDeco, update ? update.changes : _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.ChangeSet.empty(this.state.doc.length)));\n        let prevHeight = this.heightMap.height;\n        let scrollAnchor = this.scrolledToBottom ? null : this.scrollAnchorAt(this.scrollTop);\n        this.heightMap = this.heightMap.applyChanges(this.stateDeco, update.startState.doc, this.heightOracle.setDoc(this.state.doc), heightChanges);\n        if (this.heightMap.height != prevHeight)\n            update.flags |= 2 /* UpdateFlag.Height */;\n        if (scrollAnchor) {\n            this.scrollAnchorPos = update.changes.mapPos(scrollAnchor.from, -1);\n            this.scrollAnchorHeight = scrollAnchor.top;\n        }\n        else {\n            this.scrollAnchorPos = -1;\n            this.scrollAnchorHeight = this.heightMap.height;\n        }\n        let viewport = heightChanges.length ? this.mapViewport(this.viewport, update.changes) : this.viewport;\n        if (scrollTarget && (scrollTarget.range.head < viewport.from || scrollTarget.range.head > viewport.to) ||\n            !this.viewportIsAppropriate(viewport))\n            viewport = this.getViewport(0, scrollTarget);\n        let viewportChange = viewport.from != this.viewport.from || viewport.to != this.viewport.to;\n        this.viewport = viewport;\n        update.flags |= this.updateForViewport();\n        if (viewportChange || !update.changes.empty || (update.flags & 2 /* UpdateFlag.Height */))\n            this.updateViewportLines();\n        if (this.lineGaps.length || this.viewport.to - this.viewport.from > (2000 /* LG.Margin */ << 1))\n            this.updateLineGaps(this.ensureLineGaps(this.mapLineGaps(this.lineGaps, update.changes)));\n        update.flags |= this.computeVisibleRanges();\n        if (scrollTarget)\n            this.scrollTarget = scrollTarget;\n        if (!this.mustEnforceCursorAssoc && update.selectionSet && update.view.lineWrapping &&\n            update.state.selection.main.empty && update.state.selection.main.assoc &&\n            !update.state.facet(nativeSelectionHidden))\n            this.mustEnforceCursorAssoc = true;\n    }\n    measure(view) {\n        let dom = view.contentDOM, style = window.getComputedStyle(dom);\n        let oracle = this.heightOracle;\n        let whiteSpace = style.whiteSpace;\n        this.defaultTextDirection = style.direction == \"rtl\" ? Direction.RTL : Direction.LTR;\n        let refresh = this.heightOracle.mustRefreshForWrapping(whiteSpace);\n        let domRect = dom.getBoundingClientRect();\n        let measureContent = refresh || this.mustMeasureContent || this.contentDOMHeight != domRect.height;\n        this.contentDOMHeight = domRect.height;\n        this.mustMeasureContent = false;\n        let result = 0, bias = 0;\n        if (domRect.width && domRect.height) {\n            let { scaleX, scaleY } = getScale(dom, domRect);\n            if (scaleX > .005 && Math.abs(this.scaleX - scaleX) > .005 ||\n                scaleY > .005 && Math.abs(this.scaleY - scaleY) > .005) {\n                this.scaleX = scaleX;\n                this.scaleY = scaleY;\n                result |= 8 /* UpdateFlag.Geometry */;\n                refresh = measureContent = true;\n            }\n        }\n        // Vertical padding\n        let paddingTop = (parseInt(style.paddingTop) || 0) * this.scaleY;\n        let paddingBottom = (parseInt(style.paddingBottom) || 0) * this.scaleY;\n        if (this.paddingTop != paddingTop || this.paddingBottom != paddingBottom) {\n            this.paddingTop = paddingTop;\n            this.paddingBottom = paddingBottom;\n            result |= 8 /* UpdateFlag.Geometry */ | 2 /* UpdateFlag.Height */;\n        }\n        if (this.editorWidth != view.scrollDOM.clientWidth) {\n            if (oracle.lineWrapping)\n                measureContent = true;\n            this.editorWidth = view.scrollDOM.clientWidth;\n            result |= 8 /* UpdateFlag.Geometry */;\n        }\n        let scrollTop = view.scrollDOM.scrollTop * this.scaleY;\n        if (this.scrollTop != scrollTop) {\n            this.scrollAnchorHeight = -1;\n            this.scrollTop = scrollTop;\n        }\n        this.scrolledToBottom = isScrolledToBottom(view.scrollDOM);\n        // Pixel viewport\n        let pixelViewport = (this.printing ? fullPixelRange : visiblePixelRange)(dom, this.paddingTop);\n        let dTop = pixelViewport.top - this.pixelViewport.top, dBottom = pixelViewport.bottom - this.pixelViewport.bottom;\n        this.pixelViewport = pixelViewport;\n        let inView = this.pixelViewport.bottom > this.pixelViewport.top && this.pixelViewport.right > this.pixelViewport.left;\n        if (inView != this.inView) {\n            this.inView = inView;\n            if (inView)\n                measureContent = true;\n        }\n        if (!this.inView && !this.scrollTarget)\n            return 0;\n        let contentWidth = domRect.width;\n        if (this.contentDOMWidth != contentWidth || this.editorHeight != view.scrollDOM.clientHeight) {\n            this.contentDOMWidth = domRect.width;\n            this.editorHeight = view.scrollDOM.clientHeight;\n            result |= 8 /* UpdateFlag.Geometry */;\n        }\n        if (measureContent) {\n            let lineHeights = view.docView.measureVisibleLineHeights(this.viewport);\n            if (oracle.mustRefreshForHeights(lineHeights))\n                refresh = true;\n            if (refresh || oracle.lineWrapping && Math.abs(contentWidth - this.contentDOMWidth) > oracle.charWidth) {\n                let { lineHeight, charWidth, textHeight } = view.docView.measureTextSize();\n                refresh = lineHeight > 0 && oracle.refresh(whiteSpace, lineHeight, charWidth, textHeight, contentWidth / charWidth, lineHeights);\n                if (refresh) {\n                    view.docView.minWidth = 0;\n                    result |= 8 /* UpdateFlag.Geometry */;\n                }\n            }\n            if (dTop > 0 && dBottom > 0)\n                bias = Math.max(dTop, dBottom);\n            else if (dTop < 0 && dBottom < 0)\n                bias = Math.min(dTop, dBottom);\n            oracle.heightChanged = false;\n            for (let vp of this.viewports) {\n                let heights = vp.from == this.viewport.from ? lineHeights : view.docView.measureVisibleLineHeights(vp);\n                this.heightMap = (refresh ? HeightMap.empty().applyChanges(this.stateDeco, _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.Text.empty, this.heightOracle, [new ChangedRange(0, 0, 0, view.state.doc.length)]) : this.heightMap).updateHeight(oracle, 0, refresh, new MeasuredHeights(vp.from, heights));\n            }\n            if (oracle.heightChanged)\n                result |= 2 /* UpdateFlag.Height */;\n        }\n        let viewportChange = !this.viewportIsAppropriate(this.viewport, bias) ||\n            this.scrollTarget && (this.scrollTarget.range.head < this.viewport.from ||\n                this.scrollTarget.range.head > this.viewport.to);\n        if (viewportChange) {\n            if (result & 2 /* UpdateFlag.Height */)\n                result |= this.updateScaler();\n            this.viewport = this.getViewport(bias, this.scrollTarget);\n            result |= this.updateForViewport();\n        }\n        if ((result & 2 /* UpdateFlag.Height */) || viewportChange)\n            this.updateViewportLines();\n        if (this.lineGaps.length || this.viewport.to - this.viewport.from > (2000 /* LG.Margin */ << 1))\n            this.updateLineGaps(this.ensureLineGaps(refresh ? [] : this.lineGaps, view));\n        result |= this.computeVisibleRanges();\n        if (this.mustEnforceCursorAssoc) {\n            this.mustEnforceCursorAssoc = false;\n            // This is done in the read stage, because moving the selection\n            // to a line end is going to trigger a layout anyway, so it\n            // can't be a pure write. It should be rare that it does any\n            // writing.\n            view.docView.enforceCursorAssoc();\n        }\n        return result;\n    }\n    get visibleTop() { return this.scaler.fromDOM(this.pixelViewport.top); }\n    get visibleBottom() { return this.scaler.fromDOM(this.pixelViewport.bottom); }\n    getViewport(bias, scrollTarget) {\n        // This will divide VP.Margin between the top and the\n        // bottom, depending on the bias (the change in viewport position\n        // since the last update). It'll hold a number between 0 and 1\n        let marginTop = 0.5 - Math.max(-0.5, Math.min(0.5, bias / 1000 /* VP.Margin */ / 2));\n        let map = this.heightMap, oracle = this.heightOracle;\n        let { visibleTop, visibleBottom } = this;\n        let viewport = new Viewport(map.lineAt(visibleTop - marginTop * 1000 /* VP.Margin */, QueryType.ByHeight, oracle, 0, 0).from, map.lineAt(visibleBottom + (1 - marginTop) * 1000 /* VP.Margin */, QueryType.ByHeight, oracle, 0, 0).to);\n        // If scrollTarget is given, make sure the viewport includes that position\n        if (scrollTarget) {\n            let { head } = scrollTarget.range;\n            if (head < viewport.from || head > viewport.to) {\n                let viewHeight = Math.min(this.editorHeight, this.pixelViewport.bottom - this.pixelViewport.top);\n                let block = map.lineAt(head, QueryType.ByPos, oracle, 0, 0), topPos;\n                if (scrollTarget.y == \"center\")\n                    topPos = (block.top + block.bottom) / 2 - viewHeight / 2;\n                else if (scrollTarget.y == \"start\" || scrollTarget.y == \"nearest\" && head < viewport.from)\n                    topPos = block.top;\n                else\n                    topPos = block.bottom - viewHeight;\n                viewport = new Viewport(map.lineAt(topPos - 1000 /* VP.Margin */ / 2, QueryType.ByHeight, oracle, 0, 0).from, map.lineAt(topPos + viewHeight + 1000 /* VP.Margin */ / 2, QueryType.ByHeight, oracle, 0, 0).to);\n            }\n        }\n        return viewport;\n    }\n    mapViewport(viewport, changes) {\n        let from = changes.mapPos(viewport.from, -1), to = changes.mapPos(viewport.to, 1);\n        return new Viewport(this.heightMap.lineAt(from, QueryType.ByPos, this.heightOracle, 0, 0).from, this.heightMap.lineAt(to, QueryType.ByPos, this.heightOracle, 0, 0).to);\n    }\n    // Checks if a given viewport covers the visible part of the\n    // document and not too much beyond that.\n    viewportIsAppropriate({ from, to }, bias = 0) {\n        if (!this.inView)\n            return true;\n        let { top } = this.heightMap.lineAt(from, QueryType.ByPos, this.heightOracle, 0, 0);\n        let { bottom } = this.heightMap.lineAt(to, QueryType.ByPos, this.heightOracle, 0, 0);\n        let { visibleTop, visibleBottom } = this;\n        return (from == 0 || top <= visibleTop - Math.max(10 /* VP.MinCoverMargin */, Math.min(-bias, 250 /* VP.MaxCoverMargin */))) &&\n            (to == this.state.doc.length ||\n                bottom >= visibleBottom + Math.max(10 /* VP.MinCoverMargin */, Math.min(bias, 250 /* VP.MaxCoverMargin */))) &&\n            (top > visibleTop - 2 * 1000 /* VP.Margin */ && bottom < visibleBottom + 2 * 1000 /* VP.Margin */);\n    }\n    mapLineGaps(gaps, changes) {\n        if (!gaps.length || changes.empty)\n            return gaps;\n        let mapped = [];\n        for (let gap of gaps)\n            if (!changes.touchesRange(gap.from, gap.to))\n                mapped.push(new LineGap(changes.mapPos(gap.from), changes.mapPos(gap.to), gap.size));\n        return mapped;\n    }\n    // Computes positions in the viewport where the start or end of a\n    // line should be hidden, trying to reuse existing line gaps when\n    // appropriate to avoid unneccesary redraws.\n    // Uses crude character-counting for the positioning and sizing,\n    // since actual DOM coordinates aren't always available and\n    // predictable. Relies on generous margins (see LG.Margin) to hide\n    // the artifacts this might produce from the user.\n    ensureLineGaps(current, mayMeasure) {\n        let wrapping = this.heightOracle.lineWrapping;\n        let margin = wrapping ? 10000 /* LG.MarginWrap */ : 2000 /* LG.Margin */, halfMargin = margin >> 1, doubleMargin = margin << 1;\n        // The non-wrapping logic won't work at all in predominantly right-to-left text.\n        if (this.defaultTextDirection != Direction.LTR && !wrapping)\n            return [];\n        let gaps = [];\n        let addGap = (from, to, line, structure) => {\n            if (to - from < halfMargin)\n                return;\n            let sel = this.state.selection.main, avoid = [sel.from];\n            if (!sel.empty)\n                avoid.push(sel.to);\n            for (let pos of avoid) {\n                if (pos > from && pos < to) {\n                    addGap(from, pos - 10 /* LG.SelectionMargin */, line, structure);\n                    addGap(pos + 10 /* LG.SelectionMargin */, to, line, structure);\n                    return;\n                }\n            }\n            let gap = find(current, gap => gap.from >= line.from && gap.to <= line.to &&\n                Math.abs(gap.from - from) < halfMargin && Math.abs(gap.to - to) < halfMargin &&\n                !avoid.some(pos => gap.from < pos && gap.to > pos));\n            if (!gap) {\n                // When scrolling down, snap gap ends to line starts to avoid shifts in wrapping\n                if (to < line.to && mayMeasure && wrapping &&\n                    mayMeasure.visibleRanges.some(r => r.from <= to && r.to >= to)) {\n                    let lineStart = mayMeasure.moveToLineBoundary(_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.EditorSelection.cursor(to), false, true).head;\n                    if (lineStart > from)\n                        to = lineStart;\n                }\n                gap = new LineGap(from, to, this.gapSize(line, from, to, structure));\n            }\n            gaps.push(gap);\n        };\n        let checkLine = (line) => {\n            if (line.length < doubleMargin || line.type != BlockType.Text)\n                return;\n            let structure = lineStructure(line.from, line.to, this.stateDeco);\n            if (structure.total < doubleMargin)\n                return;\n            let target = this.scrollTarget ? this.scrollTarget.range.head : null;\n            let viewFrom, viewTo;\n            if (wrapping) {\n                let marginHeight = (margin / this.heightOracle.lineLength) * this.heightOracle.lineHeight;\n                let top, bot;\n                if (target != null) {\n                    let targetFrac = findFraction(structure, target);\n                    let spaceFrac = ((this.visibleBottom - this.visibleTop) / 2 + marginHeight) / line.height;\n                    top = targetFrac - spaceFrac;\n                    bot = targetFrac + spaceFrac;\n                }\n                else {\n                    top = (this.visibleTop - line.top - marginHeight) / line.height;\n                    bot = (this.visibleBottom - line.top + marginHeight) / line.height;\n                }\n                viewFrom = findPosition(structure, top);\n                viewTo = findPosition(structure, bot);\n            }\n            else {\n                let totalWidth = structure.total * this.heightOracle.charWidth;\n                let marginWidth = margin * this.heightOracle.charWidth;\n                let left, right;\n                if (target != null) {\n                    let targetFrac = findFraction(structure, target);\n                    let spaceFrac = ((this.pixelViewport.right - this.pixelViewport.left) / 2 + marginWidth) / totalWidth;\n                    left = targetFrac - spaceFrac;\n                    right = targetFrac + spaceFrac;\n                }\n                else {\n                    left = (this.pixelViewport.left - marginWidth) / totalWidth;\n                    right = (this.pixelViewport.right + marginWidth) / totalWidth;\n                }\n                viewFrom = findPosition(structure, left);\n                viewTo = findPosition(structure, right);\n            }\n            if (viewFrom > line.from)\n                addGap(line.from, viewFrom, line, structure);\n            if (viewTo < line.to)\n                addGap(viewTo, line.to, line, structure);\n        };\n        for (let line of this.viewportLines) {\n            if (Array.isArray(line.type))\n                line.type.forEach(checkLine);\n            else\n                checkLine(line);\n        }\n        return gaps;\n    }\n    gapSize(line, from, to, structure) {\n        let fraction = findFraction(structure, to) - findFraction(structure, from);\n        if (this.heightOracle.lineWrapping) {\n            return line.height * fraction;\n        }\n        else {\n            return structure.total * this.heightOracle.charWidth * fraction;\n        }\n    }\n    updateLineGaps(gaps) {\n        if (!LineGap.same(gaps, this.lineGaps)) {\n            this.lineGaps = gaps;\n            this.lineGapDeco = Decoration.set(gaps.map(gap => gap.draw(this, this.heightOracle.lineWrapping)));\n        }\n    }\n    computeVisibleRanges() {\n        let deco = this.stateDeco;\n        if (this.lineGaps.length)\n            deco = deco.concat(this.lineGapDeco);\n        let ranges = [];\n        _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.RangeSet.spans(deco, this.viewport.from, this.viewport.to, {\n            span(from, to) { ranges.push({ from, to }); },\n            point() { }\n        }, 20);\n        let changed = ranges.length != this.visibleRanges.length ||\n            this.visibleRanges.some((r, i) => r.from != ranges[i].from || r.to != ranges[i].to);\n        this.visibleRanges = ranges;\n        return changed ? 4 /* UpdateFlag.Viewport */ : 0;\n    }\n    lineBlockAt(pos) {\n        return (pos >= this.viewport.from && pos <= this.viewport.to &&\n            this.viewportLines.find(b => b.from <= pos && b.to >= pos)) ||\n            scaleBlock(this.heightMap.lineAt(pos, QueryType.ByPos, this.heightOracle, 0, 0), this.scaler);\n    }\n    lineBlockAtHeight(height) {\n        return (height >= this.viewportLines[0].top && height <= this.viewportLines[this.viewportLines.length - 1].bottom &&\n            this.viewportLines.find(l => l.top <= height && l.bottom >= height)) ||\n            scaleBlock(this.heightMap.lineAt(this.scaler.fromDOM(height), QueryType.ByHeight, this.heightOracle, 0, 0), this.scaler);\n    }\n    scrollAnchorAt(scrollTop) {\n        let block = this.lineBlockAtHeight(scrollTop + 8);\n        return block.from >= this.viewport.from || this.viewportLines[0].top - scrollTop > 200 ? block : this.viewportLines[0];\n    }\n    elementAtHeight(height) {\n        return scaleBlock(this.heightMap.blockAt(this.scaler.fromDOM(height), this.heightOracle, 0, 0), this.scaler);\n    }\n    get docHeight() {\n        return this.scaler.toDOM(this.heightMap.height);\n    }\n    get contentHeight() {\n        return this.docHeight + this.paddingTop + this.paddingBottom;\n    }\n}\nclass Viewport {\n    constructor(from, to) {\n        this.from = from;\n        this.to = to;\n    }\n}\nfunction lineStructure(from, to, stateDeco) {\n    let ranges = [], pos = from, total = 0;\n    _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.RangeSet.spans(stateDeco, from, to, {\n        span() { },\n        point(from, to) {\n            if (from > pos) {\n                ranges.push({ from: pos, to: from });\n                total += from - pos;\n            }\n            pos = to;\n        }\n    }, 20); // We're only interested in collapsed ranges of a significant size\n    if (pos < to) {\n        ranges.push({ from: pos, to });\n        total += to - pos;\n    }\n    return { total, ranges };\n}\nfunction findPosition({ total, ranges }, ratio) {\n    if (ratio <= 0)\n        return ranges[0].from;\n    if (ratio >= 1)\n        return ranges[ranges.length - 1].to;\n    let dist = Math.floor(total * ratio);\n    for (let i = 0;; i++) {\n        let { from, to } = ranges[i], size = to - from;\n        if (dist <= size)\n            return from + dist;\n        dist -= size;\n    }\n}\nfunction findFraction(structure, pos) {\n    let counted = 0;\n    for (let { from, to } of structure.ranges) {\n        if (pos <= to) {\n            counted += pos - from;\n            break;\n        }\n        counted += to - from;\n    }\n    return counted / structure.total;\n}\nfunction find(array, f) {\n    for (let val of array)\n        if (f(val))\n            return val;\n    return undefined;\n}\n// Don't scale when the document height is within the range of what\n// the DOM can handle.\nconst IdScaler = {\n    toDOM(n) { return n; },\n    fromDOM(n) { return n; },\n    scale: 1,\n    eq(other) { return other == this; }\n};\n// When the height is too big (> VP.MaxDOMHeight), scale down the\n// regions outside the viewports so that the total height is\n// VP.MaxDOMHeight.\nclass BigScaler {\n    constructor(oracle, heightMap, viewports) {\n        let vpHeight = 0, base = 0, domBase = 0;\n        this.viewports = viewports.map(({ from, to }) => {\n            let top = heightMap.lineAt(from, QueryType.ByPos, oracle, 0, 0).top;\n            let bottom = heightMap.lineAt(to, QueryType.ByPos, oracle, 0, 0).bottom;\n            vpHeight += bottom - top;\n            return { from, to, top, bottom, domTop: 0, domBottom: 0 };\n        });\n        this.scale = (7000000 /* VP.MaxDOMHeight */ - vpHeight) / (heightMap.height - vpHeight);\n        for (let obj of this.viewports) {\n            obj.domTop = domBase + (obj.top - base) * this.scale;\n            domBase = obj.domBottom = obj.domTop + (obj.bottom - obj.top);\n            base = obj.bottom;\n        }\n    }\n    toDOM(n) {\n        for (let i = 0, base = 0, domBase = 0;; i++) {\n            let vp = i < this.viewports.length ? this.viewports[i] : null;\n            if (!vp || n < vp.top)\n                return domBase + (n - base) * this.scale;\n            if (n <= vp.bottom)\n                return vp.domTop + (n - vp.top);\n            base = vp.bottom;\n            domBase = vp.domBottom;\n        }\n    }\n    fromDOM(n) {\n        for (let i = 0, base = 0, domBase = 0;; i++) {\n            let vp = i < this.viewports.length ? this.viewports[i] : null;\n            if (!vp || n < vp.domTop)\n                return base + (n - domBase) / this.scale;\n            if (n <= vp.domBottom)\n                return vp.top + (n - vp.domTop);\n            base = vp.bottom;\n            domBase = vp.domBottom;\n        }\n    }\n    eq(other) {\n        if (!(other instanceof BigScaler))\n            return false;\n        return this.scale == other.scale && this.viewports.length == other.viewports.length &&\n            this.viewports.every((vp, i) => vp.from == other.viewports[i].from && vp.to == other.viewports[i].to);\n    }\n}\nfunction scaleBlock(block, scaler) {\n    if (scaler.scale == 1)\n        return block;\n    let bTop = scaler.toDOM(block.top), bBottom = scaler.toDOM(block.bottom);\n    return new BlockInfo(block.from, block.length, bTop, bBottom - bTop, Array.isArray(block._content) ? block._content.map(b => scaleBlock(b, scaler)) : block._content);\n}\n\nconst theme = /*@__PURE__*/_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.Facet.define({ combine: strs => strs.join(\" \") });\nconst darkTheme = /*@__PURE__*/_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.Facet.define({ combine: values => values.indexOf(true) > -1 });\nconst baseThemeID = /*@__PURE__*/style_mod__WEBPACK_IMPORTED_MODULE_0__.StyleModule.newName(), baseLightID = /*@__PURE__*/style_mod__WEBPACK_IMPORTED_MODULE_0__.StyleModule.newName(), baseDarkID = /*@__PURE__*/style_mod__WEBPACK_IMPORTED_MODULE_0__.StyleModule.newName();\nconst lightDarkIDs = { \"&light\": \".\" + baseLightID, \"&dark\": \".\" + baseDarkID };\nfunction buildTheme(main, spec, scopes) {\n    return new style_mod__WEBPACK_IMPORTED_MODULE_0__.StyleModule(spec, {\n        finish(sel) {\n            return /&/.test(sel) ? sel.replace(/&\\w*/, m => {\n                if (m == \"&\")\n                    return main;\n                if (!scopes || !scopes[m])\n                    throw new RangeError(`Unsupported selector: ${m}`);\n                return scopes[m];\n            }) : main + \" \" + sel;\n        }\n    });\n}\nconst baseTheme$1 = /*@__PURE__*/buildTheme(\".\" + baseThemeID, {\n    \"&\": {\n        position: \"relative !important\",\n        boxSizing: \"border-box\",\n        \"&.cm-focused\": {\n            // Provide a simple default outline to make sure a focused\n            // editor is visually distinct. Can't leave the default behavior\n            // because that will apply to the content element, which is\n            // inside the scrollable container and doesn't include the\n            // gutters. We also can't use an 'auto' outline, since those\n            // are, for some reason, drawn behind the element content, which\n            // will cause things like the active line background to cover\n            // the outline (#297).\n            outline: \"1px dotted #212121\"\n        },\n        display: \"flex !important\",\n        flexDirection: \"column\"\n    },\n    \".cm-scroller\": {\n        display: \"flex !important\",\n        alignItems: \"flex-start !important\",\n        fontFamily: \"monospace\",\n        lineHeight: 1.4,\n        height: \"100%\",\n        overflowX: \"auto\",\n        position: \"relative\",\n        zIndex: 0\n    },\n    \".cm-content\": {\n        margin: 0,\n        flexGrow: 2,\n        flexShrink: 0,\n        display: \"block\",\n        whiteSpace: \"pre\",\n        wordWrap: \"normal\", // https://github.com/codemirror/dev/issues/456\n        boxSizing: \"border-box\",\n        minHeight: \"100%\",\n        padding: \"4px 0\",\n        outline: \"none\",\n        \"&[contenteditable=true]\": {\n            WebkitUserModify: \"read-write-plaintext-only\",\n        }\n    },\n    \".cm-lineWrapping\": {\n        whiteSpace_fallback: \"pre-wrap\", // For IE\n        whiteSpace: \"break-spaces\",\n        wordBreak: \"break-word\", // For Safari, which doesn't support overflow-wrap: anywhere\n        overflowWrap: \"anywhere\",\n        flexShrink: 1\n    },\n    \"&light .cm-content\": { caretColor: \"black\" },\n    \"&dark .cm-content\": { caretColor: \"white\" },\n    \".cm-line\": {\n        display: \"block\",\n        padding: \"0 2px 0 6px\"\n    },\n    \".cm-layer\": {\n        position: \"absolute\",\n        left: 0,\n        top: 0,\n        contain: \"size style\",\n        \"& > *\": {\n            position: \"absolute\"\n        }\n    },\n    \"&light .cm-selectionBackground\": {\n        background: \"#d9d9d9\"\n    },\n    \"&dark .cm-selectionBackground\": {\n        background: \"#222\"\n    },\n    \"&light.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground\": {\n        background: \"#d7d4f0\"\n    },\n    \"&dark.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground\": {\n        background: \"#233\"\n    },\n    \".cm-cursorLayer\": {\n        pointerEvents: \"none\"\n    },\n    \"&.cm-focused > .cm-scroller > .cm-cursorLayer\": {\n        animation: \"steps(1) cm-blink 1.2s infinite\"\n    },\n    // Two animations defined so that we can switch between them to\n    // restart the animation without forcing another style\n    // recomputation.\n    \"@keyframes cm-blink\": { \"0%\": {}, \"50%\": { opacity: 0 }, \"100%\": {} },\n    \"@keyframes cm-blink2\": { \"0%\": {}, \"50%\": { opacity: 0 }, \"100%\": {} },\n    \".cm-cursor, .cm-dropCursor\": {\n        borderLeft: \"1.2px solid black\",\n        marginLeft: \"-0.6px\",\n        pointerEvents: \"none\",\n    },\n    \".cm-cursor\": {\n        display: \"none\"\n    },\n    \"&dark .cm-cursor\": {\n        borderLeftColor: \"#444\"\n    },\n    \".cm-dropCursor\": {\n        position: \"absolute\"\n    },\n    \"&.cm-focused > .cm-scroller > .cm-cursorLayer .cm-cursor\": {\n        display: \"block\"\n    },\n    \".cm-iso\": {\n        unicodeBidi: \"isolate\"\n    },\n    \".cm-announced\": {\n        position: \"fixed\",\n        top: \"-10000px\"\n    },\n    \"@media print\": {\n        \".cm-announced\": { display: \"none\" }\n    },\n    \"&light .cm-activeLine\": { backgroundColor: \"#cceeff44\" },\n    \"&dark .cm-activeLine\": { backgroundColor: \"#99eeff33\" },\n    \"&light .cm-specialChar\": { color: \"red\" },\n    \"&dark .cm-specialChar\": { color: \"#f78\" },\n    \".cm-gutters\": {\n        flexShrink: 0,\n        display: \"flex\",\n        height: \"100%\",\n        boxSizing: \"border-box\",\n        insetInlineStart: 0,\n        zIndex: 200\n    },\n    \"&light .cm-gutters\": {\n        backgroundColor: \"#f5f5f5\",\n        color: \"#6c6c6c\",\n        borderRight: \"1px solid #ddd\"\n    },\n    \"&dark .cm-gutters\": {\n        backgroundColor: \"#333338\",\n        color: \"#ccc\"\n    },\n    \".cm-gutter\": {\n        display: \"flex !important\", // Necessary -- prevents margin collapsing\n        flexDirection: \"column\",\n        flexShrink: 0,\n        boxSizing: \"border-box\",\n        minHeight: \"100%\",\n        overflow: \"hidden\"\n    },\n    \".cm-gutterElement\": {\n        boxSizing: \"border-box\"\n    },\n    \".cm-lineNumbers .cm-gutterElement\": {\n        padding: \"0 3px 0 5px\",\n        minWidth: \"20px\",\n        textAlign: \"right\",\n        whiteSpace: \"nowrap\"\n    },\n    \"&light .cm-activeLineGutter\": {\n        backgroundColor: \"#e2f2ff\"\n    },\n    \"&dark .cm-activeLineGutter\": {\n        backgroundColor: \"#222227\"\n    },\n    \".cm-panels\": {\n        boxSizing: \"border-box\",\n        position: \"sticky\",\n        left: 0,\n        right: 0\n    },\n    \"&light .cm-panels\": {\n        backgroundColor: \"#f5f5f5\",\n        color: \"black\"\n    },\n    \"&light .cm-panels-top\": {\n        borderBottom: \"1px solid #ddd\"\n    },\n    \"&light .cm-panels-bottom\": {\n        borderTop: \"1px solid #ddd\"\n    },\n    \"&dark .cm-panels\": {\n        backgroundColor: \"#333338\",\n        color: \"white\"\n    },\n    \".cm-tab\": {\n        display: \"inline-block\",\n        overflow: \"hidden\",\n        verticalAlign: \"bottom\"\n    },\n    \".cm-widgetBuffer\": {\n        verticalAlign: \"text-top\",\n        height: \"1em\",\n        width: 0,\n        display: \"inline\"\n    },\n    \".cm-placeholder\": {\n        color: \"#888\",\n        display: \"inline-block\",\n        verticalAlign: \"top\",\n    },\n    \".cm-highlightSpace:before\": {\n        content: \"attr(data-display)\",\n        position: \"absolute\",\n        pointerEvents: \"none\",\n        color: \"#888\"\n    },\n    \".cm-highlightTab\": {\n        backgroundImage: `url('data:image/svg+xml,<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"200\" height=\"20\"><path stroke=\"%23888\" stroke-width=\"1\" fill=\"none\" d=\"M1 10H196L190 5M190 15L196 10M197 4L197 16\"/></svg>')`,\n        backgroundSize: \"auto 100%\",\n        backgroundPosition: \"right 90%\",\n        backgroundRepeat: \"no-repeat\"\n    },\n    \".cm-trailingSpace\": {\n        backgroundColor: \"#ff332255\"\n    },\n    \".cm-button\": {\n        verticalAlign: \"middle\",\n        color: \"inherit\",\n        fontSize: \"70%\",\n        padding: \".2em 1em\",\n        borderRadius: \"1px\"\n    },\n    \"&light .cm-button\": {\n        backgroundImage: \"linear-gradient(#eff1f5, #d9d9df)\",\n        border: \"1px solid #888\",\n        \"&:active\": {\n            backgroundImage: \"linear-gradient(#b4b4b4, #d0d3d6)\"\n        }\n    },\n    \"&dark .cm-button\": {\n        backgroundImage: \"linear-gradient(#393939, #111)\",\n        border: \"1px solid #888\",\n        \"&:active\": {\n            backgroundImage: \"linear-gradient(#111, #333)\"\n        }\n    },\n    \".cm-textfield\": {\n        verticalAlign: \"middle\",\n        color: \"inherit\",\n        fontSize: \"70%\",\n        border: \"1px solid silver\",\n        padding: \".2em .5em\"\n    },\n    \"&light .cm-textfield\": {\n        backgroundColor: \"white\"\n    },\n    \"&dark .cm-textfield\": {\n        border: \"1px solid #555\",\n        backgroundColor: \"inherit\"\n    }\n}, lightDarkIDs);\n\nconst LineBreakPlaceholder = \"\\uffff\";\nclass DOMReader {\n    constructor(points, state) {\n        this.points = points;\n        this.text = \"\";\n        this.lineSeparator = state.facet(_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.EditorState.lineSeparator);\n    }\n    append(text) {\n        this.text += text;\n    }\n    lineBreak() {\n        this.text += LineBreakPlaceholder;\n    }\n    readRange(start, end) {\n        if (!start)\n            return this;\n        let parent = start.parentNode;\n        for (let cur = start;;) {\n            this.findPointBefore(parent, cur);\n            let oldLen = this.text.length;\n            this.readNode(cur);\n            let next = cur.nextSibling;\n            if (next == end)\n                break;\n            let view = ContentView.get(cur), nextView = ContentView.get(next);\n            if (view && nextView ? view.breakAfter :\n                (view ? view.breakAfter : isBlockElement(cur)) ||\n                    (isBlockElement(next) && (cur.nodeName != \"BR\" || cur.cmIgnore) && this.text.length > oldLen))\n                this.lineBreak();\n            cur = next;\n        }\n        this.findPointBefore(parent, end);\n        return this;\n    }\n    readTextNode(node) {\n        let text = node.nodeValue;\n        for (let point of this.points)\n            if (point.node == node)\n                point.pos = this.text.length + Math.min(point.offset, text.length);\n        for (let off = 0, re = this.lineSeparator ? null : /\\r\\n?|\\n/g;;) {\n            let nextBreak = -1, breakSize = 1, m;\n            if (this.lineSeparator) {\n                nextBreak = text.indexOf(this.lineSeparator, off);\n                breakSize = this.lineSeparator.length;\n            }\n            else if (m = re.exec(text)) {\n                nextBreak = m.index;\n                breakSize = m[0].length;\n            }\n            this.append(text.slice(off, nextBreak < 0 ? text.length : nextBreak));\n            if (nextBreak < 0)\n                break;\n            this.lineBreak();\n            if (breakSize > 1)\n                for (let point of this.points)\n                    if (point.node == node && point.pos > this.text.length)\n                        point.pos -= breakSize - 1;\n            off = nextBreak + breakSize;\n        }\n    }\n    readNode(node) {\n        if (node.cmIgnore)\n            return;\n        let view = ContentView.get(node);\n        let fromView = view && view.overrideDOMText;\n        if (fromView != null) {\n            this.findPointInside(node, fromView.length);\n            for (let i = fromView.iter(); !i.next().done;) {\n                if (i.lineBreak)\n                    this.lineBreak();\n                else\n                    this.append(i.value);\n            }\n        }\n        else if (node.nodeType == 3) {\n            this.readTextNode(node);\n        }\n        else if (node.nodeName == \"BR\") {\n            if (node.nextSibling)\n                this.lineBreak();\n        }\n        else if (node.nodeType == 1) {\n            this.readRange(node.firstChild, null);\n        }\n    }\n    findPointBefore(node, next) {\n        for (let point of this.points)\n            if (point.node == node && node.childNodes[point.offset] == next)\n                point.pos = this.text.length;\n    }\n    findPointInside(node, length) {\n        for (let point of this.points)\n            if (node.nodeType == 3 ? point.node == node : node.contains(point.node))\n                point.pos = this.text.length + (isAtEnd(node, point.node, point.offset) ? length : 0);\n    }\n}\nfunction isAtEnd(parent, node, offset) {\n    for (;;) {\n        if (!node || offset < maxOffset(node))\n            return false;\n        if (node == parent)\n            return true;\n        offset = domIndex(node) + 1;\n        node = node.parentNode;\n    }\n}\nclass DOMPoint {\n    constructor(node, offset) {\n        this.node = node;\n        this.offset = offset;\n        this.pos = -1;\n    }\n}\n\nclass DOMChange {\n    constructor(view, start, end, typeOver) {\n        this.typeOver = typeOver;\n        this.bounds = null;\n        this.text = \"\";\n        this.domChanged = start > -1;\n        let { impreciseHead: iHead, impreciseAnchor: iAnchor } = view.docView;\n        if (view.state.readOnly && start > -1) {\n            // Ignore changes when the editor is read-only\n            this.newSel = null;\n        }\n        else if (start > -1 && (this.bounds = view.docView.domBoundsAround(start, end, 0))) {\n            let selPoints = iHead || iAnchor ? [] : selectionPoints(view);\n            let reader = new DOMReader(selPoints, view.state);\n            reader.readRange(this.bounds.startDOM, this.bounds.endDOM);\n            this.text = reader.text;\n            this.newSel = selectionFromPoints(selPoints, this.bounds.from);\n        }\n        else {\n            let domSel = view.observer.selectionRange;\n            let head = iHead && iHead.node == domSel.focusNode && iHead.offset == domSel.focusOffset ||\n                !contains(view.contentDOM, domSel.focusNode)\n                ? view.state.selection.main.head\n                : view.docView.posFromDOM(domSel.focusNode, domSel.focusOffset);\n            let anchor = iAnchor && iAnchor.node == domSel.anchorNode && iAnchor.offset == domSel.anchorOffset ||\n                !contains(view.contentDOM, domSel.anchorNode)\n                ? view.state.selection.main.anchor\n                : view.docView.posFromDOM(domSel.anchorNode, domSel.anchorOffset);\n            // iOS will refuse to select the block gaps when doing\n            // select-all.\n            // Chrome will put the selection *inside* them, confusing\n            // posFromDOM\n            let vp = view.viewport;\n            if ((browser.ios || browser.chrome) && view.state.selection.main.empty && head != anchor &&\n                (vp.from > 0 || vp.to < view.state.doc.length)) {\n                let from = Math.min(head, anchor), to = Math.max(head, anchor);\n                let offFrom = vp.from - from, offTo = vp.to - to;\n                if ((offFrom == 0 || offFrom == 1 || from == 0) && (offTo == 0 || offTo == -1 || to == view.state.doc.length)) {\n                    head = 0;\n                    anchor = view.state.doc.length;\n                }\n            }\n            this.newSel = _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.EditorSelection.single(anchor, head);\n        }\n    }\n}\nfunction applyDOMChange(view, domChange) {\n    let change;\n    let { newSel } = domChange, sel = view.state.selection.main;\n    let lastKey = view.inputState.lastKeyTime > Date.now() - 100 ? view.inputState.lastKeyCode : -1;\n    if (domChange.bounds) {\n        let { from, to } = domChange.bounds;\n        let preferredPos = sel.from, preferredSide = null;\n        // Prefer anchoring to end when Backspace is pressed (or, on\n        // Android, when something was deleted)\n        if (lastKey === 8 || browser.android && domChange.text.length < to - from) {\n            preferredPos = sel.to;\n            preferredSide = \"end\";\n        }\n        let diff = findDiff(view.state.doc.sliceString(from, to, LineBreakPlaceholder), domChange.text, preferredPos - from, preferredSide);\n        if (diff) {\n            // Chrome inserts two newlines when pressing shift-enter at the\n            // end of a line. DomChange drops one of those.\n            if (browser.chrome && lastKey == 13 &&\n                diff.toB == diff.from + 2 && domChange.text.slice(diff.from, diff.toB) == LineBreakPlaceholder + LineBreakPlaceholder)\n                diff.toB--;\n            change = { from: from + diff.from, to: from + diff.toA,\n                insert: _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.Text.of(domChange.text.slice(diff.from, diff.toB).split(LineBreakPlaceholder)) };\n        }\n    }\n    else if (newSel && (!view.hasFocus && view.state.facet(editable) || newSel.main.eq(sel))) {\n        newSel = null;\n    }\n    if (!change && !newSel)\n        return false;\n    if (!change && domChange.typeOver && !sel.empty && newSel && newSel.main.empty) {\n        // Heuristic to notice typing over a selected character\n        change = { from: sel.from, to: sel.to, insert: view.state.doc.slice(sel.from, sel.to) };\n    }\n    else if (change && change.from >= sel.from && change.to <= sel.to &&\n        (change.from != sel.from || change.to != sel.to) &&\n        (sel.to - sel.from) - (change.to - change.from) <= 4) {\n        // If the change is inside the selection and covers most of it,\n        // assume it is a selection replace (with identical characters at\n        // the start/end not included in the diff)\n        change = {\n            from: sel.from, to: sel.to,\n            insert: view.state.doc.slice(sel.from, change.from).append(change.insert).append(view.state.doc.slice(change.to, sel.to))\n        };\n    }\n    else if ((browser.mac || browser.android) && change && change.from == change.to && change.from == sel.head - 1 &&\n        /^\\. ?$/.test(change.insert.toString()) && view.contentDOM.getAttribute(\"autocorrect\") == \"off\") {\n        // Detect insert-period-on-double-space Mac and Android behavior,\n        // and transform it into a regular space insert.\n        if (newSel && change.insert.length == 2)\n            newSel = _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.EditorSelection.single(newSel.main.anchor - 1, newSel.main.head - 1);\n        change = { from: sel.from, to: sel.to, insert: _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.Text.of([\" \"]) };\n    }\n    else if (browser.chrome && change && change.from == change.to && change.from == sel.head &&\n        change.insert.toString() == \"\\n \" && view.lineWrapping) {\n        // In Chrome, if you insert a space at the start of a wrapped\n        // line, it will actually insert a newline and a space, causing a\n        // bogus new line to be created in CodeMirror (#968)\n        if (newSel)\n            newSel = _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.EditorSelection.single(newSel.main.anchor - 1, newSel.main.head - 1);\n        change = { from: sel.from, to: sel.to, insert: _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.Text.of([\" \"]) };\n    }\n    if (change) {\n        return applyDOMChangeInner(view, change, newSel, lastKey);\n    }\n    else if (newSel && !newSel.main.eq(sel)) {\n        let scrollIntoView = false, userEvent = \"select\";\n        if (view.inputState.lastSelectionTime > Date.now() - 50) {\n            if (view.inputState.lastSelectionOrigin == \"select\")\n                scrollIntoView = true;\n            userEvent = view.inputState.lastSelectionOrigin;\n        }\n        view.dispatch({ selection: newSel, scrollIntoView, userEvent });\n        return true;\n    }\n    else {\n        return false;\n    }\n}\nfunction applyDOMChangeInner(view, change, newSel, lastKey = -1) {\n    if (browser.ios && view.inputState.flushIOSKey(change))\n        return true;\n    let sel = view.state.selection.main;\n    // Android browsers don't fire reasonable key events for enter,\n    // backspace, or delete. So this detects changes that look like\n    // they're caused by those keys, and reinterprets them as key\n    // events. (Some of these keys are also handled by beforeinput\n    // events and the pendingAndroidKey mechanism, but that's not\n    // reliable in all situations.)\n    if (browser.android &&\n        ((change.to == sel.to &&\n            // GBoard will sometimes remove a space it just inserted\n            // after a completion when you press enter\n            (change.from == sel.from || change.from == sel.from - 1 && view.state.sliceDoc(change.from, sel.from) == \" \") &&\n            change.insert.length == 1 && change.insert.lines == 2 &&\n            dispatchKey(view.contentDOM, \"Enter\", 13)) ||\n            ((change.from == sel.from - 1 && change.to == sel.to && change.insert.length == 0 ||\n                lastKey == 8 && change.insert.length < change.to - change.from && change.to > sel.head) &&\n                dispatchKey(view.contentDOM, \"Backspace\", 8)) ||\n            (change.from == sel.from && change.to == sel.to + 1 && change.insert.length == 0 &&\n                dispatchKey(view.contentDOM, \"Delete\", 46))))\n        return true;\n    let text = change.insert.toString();\n    if (view.inputState.composing >= 0)\n        view.inputState.composing++;\n    let defaultTr;\n    let defaultInsert = () => defaultTr || (defaultTr = applyDefaultInsert(view, change, newSel));\n    if (!view.state.facet(inputHandler).some(h => h(view, change.from, change.to, text, defaultInsert)))\n        view.dispatch(defaultInsert());\n    return true;\n}\nfunction applyDefaultInsert(view, change, newSel) {\n    let tr, startState = view.state, sel = startState.selection.main;\n    if (change.from >= sel.from && change.to <= sel.to && change.to - change.from >= (sel.to - sel.from) / 3 &&\n        (!newSel || newSel.main.empty && newSel.main.from == change.from + change.insert.length) &&\n        view.inputState.composing < 0) {\n        let before = sel.from < change.from ? startState.sliceDoc(sel.from, change.from) : \"\";\n        let after = sel.to > change.to ? startState.sliceDoc(change.to, sel.to) : \"\";\n        tr = startState.replaceSelection(view.state.toText(before + change.insert.sliceString(0, undefined, view.state.lineBreak) + after));\n    }\n    else {\n        let changes = startState.changes(change);\n        let mainSel = newSel && newSel.main.to <= changes.newLength ? newSel.main : undefined;\n        // Try to apply a composition change to all cursors\n        if (startState.selection.ranges.length > 1 && view.inputState.composing >= 0 &&\n            change.to <= sel.to && change.to >= sel.to - 10) {\n            let replaced = view.state.sliceDoc(change.from, change.to);\n            let compositionRange, composition = newSel && findCompositionNode(view, newSel.main.head);\n            if (composition) {\n                let dLen = change.insert.length - (change.to - change.from);\n                compositionRange = { from: composition.from, to: composition.to - dLen };\n            }\n            else {\n                compositionRange = view.state.doc.lineAt(sel.head);\n            }\n            let offset = sel.to - change.to, size = sel.to - sel.from;\n            tr = startState.changeByRange(range => {\n                if (range.from == sel.from && range.to == sel.to)\n                    return { changes, range: mainSel || range.map(changes) };\n                let to = range.to - offset, from = to - replaced.length;\n                if (range.to - range.from != size || view.state.sliceDoc(from, to) != replaced ||\n                    // Unfortunately, there's no way to make multiple\n                    // changes in the same node work without aborting\n                    // composition, so cursors in the composition range are\n                    // ignored.\n                    range.to >= compositionRange.from && range.from <= compositionRange.to)\n                    return { range };\n                let rangeChanges = startState.changes({ from, to, insert: change.insert }), selOff = range.to - sel.to;\n                return {\n                    changes: rangeChanges,\n                    range: !mainSel ? range.map(rangeChanges) :\n                        _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.EditorSelection.range(Math.max(0, mainSel.anchor + selOff), Math.max(0, mainSel.head + selOff))\n                };\n            });\n        }\n        else {\n            tr = {\n                changes,\n                selection: mainSel && startState.selection.replaceRange(mainSel)\n            };\n        }\n    }\n    let userEvent = \"input.type\";\n    if (view.composing ||\n        view.inputState.compositionPendingChange && view.inputState.compositionEndedAt > Date.now() - 50) {\n        view.inputState.compositionPendingChange = false;\n        userEvent += \".compose\";\n        if (view.inputState.compositionFirstChange) {\n            userEvent += \".start\";\n            view.inputState.compositionFirstChange = false;\n        }\n    }\n    return startState.update(tr, { userEvent, scrollIntoView: true });\n}\nfunction findDiff(a, b, preferredPos, preferredSide) {\n    let minLen = Math.min(a.length, b.length);\n    let from = 0;\n    while (from < minLen && a.charCodeAt(from) == b.charCodeAt(from))\n        from++;\n    if (from == minLen && a.length == b.length)\n        return null;\n    let toA = a.length, toB = b.length;\n    while (toA > 0 && toB > 0 && a.charCodeAt(toA - 1) == b.charCodeAt(toB - 1)) {\n        toA--;\n        toB--;\n    }\n    if (preferredSide == \"end\") {\n        let adjust = Math.max(0, from - Math.min(toA, toB));\n        preferredPos -= toA + adjust - from;\n    }\n    if (toA < from && a.length < b.length) {\n        let move = preferredPos <= from && preferredPos >= toA ? from - preferredPos : 0;\n        from -= move;\n        toB = from + (toB - toA);\n        toA = from;\n    }\n    else if (toB < from) {\n        let move = preferredPos <= from && preferredPos >= toB ? from - preferredPos : 0;\n        from -= move;\n        toA = from + (toA - toB);\n        toB = from;\n    }\n    return { from, toA, toB };\n}\nfunction selectionPoints(view) {\n    let result = [];\n    if (view.root.activeElement != view.contentDOM)\n        return result;\n    let { anchorNode, anchorOffset, focusNode, focusOffset } = view.observer.selectionRange;\n    if (anchorNode) {\n        result.push(new DOMPoint(anchorNode, anchorOffset));\n        if (focusNode != anchorNode || focusOffset != anchorOffset)\n            result.push(new DOMPoint(focusNode, focusOffset));\n    }\n    return result;\n}\nfunction selectionFromPoints(points, base) {\n    if (points.length == 0)\n        return null;\n    let anchor = points[0].pos, head = points.length == 2 ? points[1].pos : anchor;\n    return anchor > -1 && head > -1 ? _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.EditorSelection.single(anchor + base, head + base) : null;\n}\n\nconst observeOptions = {\n    childList: true,\n    characterData: true,\n    subtree: true,\n    attributes: true,\n    characterDataOldValue: true\n};\n// IE11 has very broken mutation observers, so we also listen to\n// DOMCharacterDataModified there\nconst useCharData = browser.ie && browser.ie_version <= 11;\nclass DOMObserver {\n    constructor(view) {\n        this.view = view;\n        this.active = false;\n        this.editContext = null;\n        // The known selection. Kept in our own object, as opposed to just\n        // directly accessing the selection because:\n        //  - Safari doesn't report the right selection in shadow DOM\n        //  - Reading from the selection forces a DOM layout\n        //  - This way, we can ignore selectionchange events if we have\n        //    already seen the 'new' selection\n        this.selectionRange = new DOMSelectionState;\n        // Set when a selection change is detected, cleared on flush\n        this.selectionChanged = false;\n        this.delayedFlush = -1;\n        this.resizeTimeout = -1;\n        this.queue = [];\n        this.delayedAndroidKey = null;\n        this.flushingAndroidKey = -1;\n        this.lastChange = 0;\n        this.scrollTargets = [];\n        this.intersection = null;\n        this.resizeScroll = null;\n        this.intersecting = false;\n        this.gapIntersection = null;\n        this.gaps = [];\n        this.printQuery = null;\n        // Timeout for scheduling check of the parents that need scroll handlers\n        this.parentCheck = -1;\n        this.dom = view.contentDOM;\n        this.observer = new MutationObserver(mutations => {\n            for (let mut of mutations)\n                this.queue.push(mut);\n            // IE11 will sometimes (on typing over a selection or\n            // backspacing out a single character text node) call the\n            // observer callback before actually updating the DOM.\n            //\n            // Unrelatedly, iOS Safari will, when ending a composition,\n            // sometimes first clear it, deliver the mutations, and then\n            // reinsert the finished text. CodeMirror's handling of the\n            // deletion will prevent the reinsertion from happening,\n            // breaking composition.\n            if ((browser.ie && browser.ie_version <= 11 || browser.ios && view.composing) &&\n                mutations.some(m => m.type == \"childList\" && m.removedNodes.length ||\n                    m.type == \"characterData\" && m.oldValue.length > m.target.nodeValue.length))\n                this.flushSoon();\n            else\n                this.flush();\n        });\n        if (window.EditContext && view.constructor.EDIT_CONTEXT !== false &&\n            // Chrome <126 doesn't support inverted selections in edit context (#1392)\n            !(browser.chrome && browser.chrome_version < 126)) {\n            this.editContext = new EditContextManager(view);\n            if (view.state.facet(editable))\n                view.contentDOM.editContext = this.editContext.editContext;\n        }\n        if (useCharData)\n            this.onCharData = (event) => {\n                this.queue.push({ target: event.target,\n                    type: \"characterData\",\n                    oldValue: event.prevValue });\n                this.flushSoon();\n            };\n        this.onSelectionChange = this.onSelectionChange.bind(this);\n        this.onResize = this.onResize.bind(this);\n        this.onPrint = this.onPrint.bind(this);\n        this.onScroll = this.onScroll.bind(this);\n        if (window.matchMedia)\n            this.printQuery = window.matchMedia(\"print\");\n        if (typeof ResizeObserver == \"function\") {\n            this.resizeScroll = new ResizeObserver(() => {\n                var _a;\n                if (((_a = this.view.docView) === null || _a === void 0 ? void 0 : _a.lastUpdate) < Date.now() - 75)\n                    this.onResize();\n            });\n            this.resizeScroll.observe(view.scrollDOM);\n        }\n        this.addWindowListeners(this.win = view.win);\n        this.start();\n        if (typeof IntersectionObserver == \"function\") {\n            this.intersection = new IntersectionObserver(entries => {\n                if (this.parentCheck < 0)\n                    this.parentCheck = setTimeout(this.listenForScroll.bind(this), 1000);\n                if (entries.length > 0 && (entries[entries.length - 1].intersectionRatio > 0) != this.intersecting) {\n                    this.intersecting = !this.intersecting;\n                    if (this.intersecting != this.view.inView)\n                        this.onScrollChanged(document.createEvent(\"Event\"));\n                }\n            }, { threshold: [0, .001] });\n            this.intersection.observe(this.dom);\n            this.gapIntersection = new IntersectionObserver(entries => {\n                if (entries.length > 0 && entries[entries.length - 1].intersectionRatio > 0)\n                    this.onScrollChanged(document.createEvent(\"Event\"));\n            }, {});\n        }\n        this.listenForScroll();\n        this.readSelectionRange();\n    }\n    onScrollChanged(e) {\n        this.view.inputState.runHandlers(\"scroll\", e);\n        if (this.intersecting)\n            this.view.measure();\n    }\n    onScroll(e) {\n        if (this.intersecting)\n            this.flush(false);\n        if (this.editContext)\n            this.view.requestMeasure(this.editContext.measureReq);\n        this.onScrollChanged(e);\n    }\n    onResize() {\n        if (this.resizeTimeout < 0)\n            this.resizeTimeout = setTimeout(() => {\n                this.resizeTimeout = -1;\n                this.view.requestMeasure();\n            }, 50);\n    }\n    onPrint(event) {\n        if (event.type == \"change\" && !event.matches)\n            return;\n        this.view.viewState.printing = true;\n        this.view.measure();\n        setTimeout(() => {\n            this.view.viewState.printing = false;\n            this.view.requestMeasure();\n        }, 500);\n    }\n    updateGaps(gaps) {\n        if (this.gapIntersection && (gaps.length != this.gaps.length || this.gaps.some((g, i) => g != gaps[i]))) {\n            this.gapIntersection.disconnect();\n            for (let gap of gaps)\n                this.gapIntersection.observe(gap);\n            this.gaps = gaps;\n        }\n    }\n    onSelectionChange(event) {\n        let wasChanged = this.selectionChanged;\n        if (!this.readSelectionRange() || this.delayedAndroidKey)\n            return;\n        let { view } = this, sel = this.selectionRange;\n        if (view.state.facet(editable) ? view.root.activeElement != this.dom : !hasSelection(view.dom, sel))\n            return;\n        let context = sel.anchorNode && view.docView.nearest(sel.anchorNode);\n        if (context && context.ignoreEvent(event)) {\n            if (!wasChanged)\n                this.selectionChanged = false;\n            return;\n        }\n        // Deletions on IE11 fire their events in the wrong order, giving\n        // us a selection change event before the DOM changes are\n        // reported.\n        // Chrome Android has a similar issue when backspacing out a\n        // selection (#645).\n        if ((browser.ie && browser.ie_version <= 11 || browser.android && browser.chrome) && !view.state.selection.main.empty &&\n            // (Selection.isCollapsed isn't reliable on IE)\n            sel.focusNode && isEquivalentPosition(sel.focusNode, sel.focusOffset, sel.anchorNode, sel.anchorOffset))\n            this.flushSoon();\n        else\n            this.flush(false);\n    }\n    readSelectionRange() {\n        let { view } = this;\n        // The Selection object is broken in shadow roots in Safari. See\n        // https://github.com/codemirror/dev/issues/414\n        let selection = getSelection(view.root);\n        if (!selection)\n            return false;\n        let range = browser.safari && view.root.nodeType == 11 &&\n            deepActiveElement(this.dom.ownerDocument) == this.dom &&\n            safariSelectionRangeHack(this.view, selection) || selection;\n        if (!range || this.selectionRange.eq(range))\n            return false;\n        let local = hasSelection(this.dom, range);\n        // Detect the situation where the browser has, on focus, moved the\n        // selection to the start of the content element. Reset it to the\n        // position from the editor state.\n        if (local && !this.selectionChanged &&\n            view.inputState.lastFocusTime > Date.now() - 200 &&\n            view.inputState.lastTouchTime < Date.now() - 300 &&\n            atElementStart(this.dom, range)) {\n            this.view.inputState.lastFocusTime = 0;\n            view.docView.updateSelection();\n            return false;\n        }\n        this.selectionRange.setRange(range);\n        if (local)\n            this.selectionChanged = true;\n        return true;\n    }\n    setSelectionRange(anchor, head) {\n        this.selectionRange.set(anchor.node, anchor.offset, head.node, head.offset);\n        this.selectionChanged = false;\n    }\n    clearSelectionRange() {\n        this.selectionRange.set(null, 0, null, 0);\n    }\n    listenForScroll() {\n        this.parentCheck = -1;\n        let i = 0, changed = null;\n        for (let dom = this.dom; dom;) {\n            if (dom.nodeType == 1) {\n                if (!changed && i < this.scrollTargets.length && this.scrollTargets[i] == dom)\n                    i++;\n                else if (!changed)\n                    changed = this.scrollTargets.slice(0, i);\n                if (changed)\n                    changed.push(dom);\n                dom = dom.assignedSlot || dom.parentNode;\n            }\n            else if (dom.nodeType == 11) { // Shadow root\n                dom = dom.host;\n            }\n            else {\n                break;\n            }\n        }\n        if (i < this.scrollTargets.length && !changed)\n            changed = this.scrollTargets.slice(0, i);\n        if (changed) {\n            for (let dom of this.scrollTargets)\n                dom.removeEventListener(\"scroll\", this.onScroll);\n            for (let dom of this.scrollTargets = changed)\n                dom.addEventListener(\"scroll\", this.onScroll);\n        }\n    }\n    ignore(f) {\n        if (!this.active)\n            return f();\n        try {\n            this.stop();\n            return f();\n        }\n        finally {\n            this.start();\n            this.clear();\n        }\n    }\n    start() {\n        if (this.active)\n            return;\n        this.observer.observe(this.dom, observeOptions);\n        if (useCharData)\n            this.dom.addEventListener(\"DOMCharacterDataModified\", this.onCharData);\n        this.active = true;\n    }\n    stop() {\n        if (!this.active)\n            return;\n        this.active = false;\n        this.observer.disconnect();\n        if (useCharData)\n            this.dom.removeEventListener(\"DOMCharacterDataModified\", this.onCharData);\n    }\n    // Throw away any pending changes\n    clear() {\n        this.processRecords();\n        this.queue.length = 0;\n        this.selectionChanged = false;\n    }\n    // Chrome Android, especially in combination with GBoard, not only\n    // doesn't reliably fire regular key events, but also often\n    // surrounds the effect of enter or backspace with a bunch of\n    // composition events that, when interrupted, cause text duplication\n    // or other kinds of corruption. This hack makes the editor back off\n    // from handling DOM changes for a moment when such a key is\n    // detected (via beforeinput or keydown), and then tries to flush\n    // them or, if that has no effect, dispatches the given key.\n    delayAndroidKey(key, keyCode) {\n        var _a;\n        if (!this.delayedAndroidKey) {\n            let flush = () => {\n                let key = this.delayedAndroidKey;\n                if (key) {\n                    this.clearDelayedAndroidKey();\n                    this.view.inputState.lastKeyCode = key.keyCode;\n                    this.view.inputState.lastKeyTime = Date.now();\n                    let flushed = this.flush();\n                    if (!flushed && key.force)\n                        dispatchKey(this.dom, key.key, key.keyCode);\n                }\n            };\n            this.flushingAndroidKey = this.view.win.requestAnimationFrame(flush);\n        }\n        // Since backspace beforeinput is sometimes signalled spuriously,\n        // Enter always takes precedence.\n        if (!this.delayedAndroidKey || key == \"Enter\")\n            this.delayedAndroidKey = {\n                key, keyCode,\n                // Only run the key handler when no changes are detected if\n                // this isn't coming right after another change, in which case\n                // it is probably part of a weird chain of updates, and should\n                // be ignored if it returns the DOM to its previous state.\n                force: this.lastChange < Date.now() - 50 || !!((_a = this.delayedAndroidKey) === null || _a === void 0 ? void 0 : _a.force)\n            };\n    }\n    clearDelayedAndroidKey() {\n        this.win.cancelAnimationFrame(this.flushingAndroidKey);\n        this.delayedAndroidKey = null;\n        this.flushingAndroidKey = -1;\n    }\n    flushSoon() {\n        if (this.delayedFlush < 0)\n            this.delayedFlush = this.view.win.requestAnimationFrame(() => { this.delayedFlush = -1; this.flush(); });\n    }\n    forceFlush() {\n        if (this.delayedFlush >= 0) {\n            this.view.win.cancelAnimationFrame(this.delayedFlush);\n            this.delayedFlush = -1;\n        }\n        this.flush();\n    }\n    pendingRecords() {\n        for (let mut of this.observer.takeRecords())\n            this.queue.push(mut);\n        return this.queue;\n    }\n    processRecords() {\n        let records = this.pendingRecords();\n        if (records.length)\n            this.queue = [];\n        let from = -1, to = -1, typeOver = false;\n        for (let record of records) {\n            let range = this.readMutation(record);\n            if (!range)\n                continue;\n            if (range.typeOver)\n                typeOver = true;\n            if (from == -1) {\n                ({ from, to } = range);\n            }\n            else {\n                from = Math.min(range.from, from);\n                to = Math.max(range.to, to);\n            }\n        }\n        return { from, to, typeOver };\n    }\n    readChange() {\n        let { from, to, typeOver } = this.processRecords();\n        let newSel = this.selectionChanged && hasSelection(this.dom, this.selectionRange);\n        if (from < 0 && !newSel)\n            return null;\n        if (from > -1)\n            this.lastChange = Date.now();\n        this.view.inputState.lastFocusTime = 0;\n        this.selectionChanged = false;\n        let change = new DOMChange(this.view, from, to, typeOver);\n        this.view.docView.domChanged = { newSel: change.newSel ? change.newSel.main : null };\n        return change;\n    }\n    // Apply pending changes, if any\n    flush(readSelection = true) {\n        // Completely hold off flushing when pending keys are set—the code\n        // managing those will make sure processRecords is called and the\n        // view is resynchronized after\n        if (this.delayedFlush >= 0 || this.delayedAndroidKey)\n            return false;\n        if (readSelection)\n            this.readSelectionRange();\n        let domChange = this.readChange();\n        if (!domChange) {\n            this.view.requestMeasure();\n            return false;\n        }\n        let startState = this.view.state;\n        let handled = applyDOMChange(this.view, domChange);\n        // The view wasn't updated but DOM/selection changes were seen. Reset the view.\n        if (this.view.state == startState &&\n            (domChange.domChanged || domChange.newSel && !domChange.newSel.main.eq(this.view.state.selection.main)))\n            this.view.update([]);\n        return handled;\n    }\n    readMutation(rec) {\n        let cView = this.view.docView.nearest(rec.target);\n        if (!cView || cView.ignoreMutation(rec))\n            return null;\n        cView.markDirty(rec.type == \"attributes\");\n        if (rec.type == \"attributes\")\n            cView.flags |= 4 /* ViewFlag.AttrsDirty */;\n        if (rec.type == \"childList\") {\n            let childBefore = findChild(cView, rec.previousSibling || rec.target.previousSibling, -1);\n            let childAfter = findChild(cView, rec.nextSibling || rec.target.nextSibling, 1);\n            return { from: childBefore ? cView.posAfter(childBefore) : cView.posAtStart,\n                to: childAfter ? cView.posBefore(childAfter) : cView.posAtEnd, typeOver: false };\n        }\n        else if (rec.type == \"characterData\") {\n            return { from: cView.posAtStart, to: cView.posAtEnd, typeOver: rec.target.nodeValue == rec.oldValue };\n        }\n        else {\n            return null;\n        }\n    }\n    setWindow(win) {\n        if (win != this.win) {\n            this.removeWindowListeners(this.win);\n            this.win = win;\n            this.addWindowListeners(this.win);\n        }\n    }\n    addWindowListeners(win) {\n        win.addEventListener(\"resize\", this.onResize);\n        if (this.printQuery)\n            this.printQuery.addEventListener(\"change\", this.onPrint);\n        else\n            win.addEventListener(\"beforeprint\", this.onPrint);\n        win.addEventListener(\"scroll\", this.onScroll);\n        win.document.addEventListener(\"selectionchange\", this.onSelectionChange);\n    }\n    removeWindowListeners(win) {\n        win.removeEventListener(\"scroll\", this.onScroll);\n        win.removeEventListener(\"resize\", this.onResize);\n        if (this.printQuery)\n            this.printQuery.removeEventListener(\"change\", this.onPrint);\n        else\n            win.removeEventListener(\"beforeprint\", this.onPrint);\n        win.document.removeEventListener(\"selectionchange\", this.onSelectionChange);\n    }\n    update(update) {\n        if (this.editContext) {\n            this.editContext.update(update);\n            if (update.startState.facet(editable) != update.state.facet(editable))\n                update.view.contentDOM.editContext = update.state.facet(editable) ? this.editContext.editContext : null;\n        }\n    }\n    destroy() {\n        var _a, _b, _c;\n        this.stop();\n        (_a = this.intersection) === null || _a === void 0 ? void 0 : _a.disconnect();\n        (_b = this.gapIntersection) === null || _b === void 0 ? void 0 : _b.disconnect();\n        (_c = this.resizeScroll) === null || _c === void 0 ? void 0 : _c.disconnect();\n        for (let dom of this.scrollTargets)\n            dom.removeEventListener(\"scroll\", this.onScroll);\n        this.removeWindowListeners(this.win);\n        clearTimeout(this.parentCheck);\n        clearTimeout(this.resizeTimeout);\n        this.win.cancelAnimationFrame(this.delayedFlush);\n        this.win.cancelAnimationFrame(this.flushingAndroidKey);\n    }\n}\nfunction findChild(cView, dom, dir) {\n    while (dom) {\n        let curView = ContentView.get(dom);\n        if (curView && curView.parent == cView)\n            return curView;\n        let parent = dom.parentNode;\n        dom = parent != cView.dom ? parent : dir > 0 ? dom.nextSibling : dom.previousSibling;\n    }\n    return null;\n}\nfunction buildSelectionRangeFromRange(view, range) {\n    let anchorNode = range.startContainer, anchorOffset = range.startOffset;\n    let focusNode = range.endContainer, focusOffset = range.endOffset;\n    let curAnchor = view.docView.domAtPos(view.state.selection.main.anchor);\n    // Since such a range doesn't distinguish between anchor and head,\n    // use a heuristic that flips it around if its end matches the\n    // current anchor.\n    if (isEquivalentPosition(curAnchor.node, curAnchor.offset, focusNode, focusOffset))\n        [anchorNode, anchorOffset, focusNode, focusOffset] = [focusNode, focusOffset, anchorNode, anchorOffset];\n    return { anchorNode, anchorOffset, focusNode, focusOffset };\n}\n// Used to work around a Safari Selection/shadow DOM bug (#414)\nfunction safariSelectionRangeHack(view, selection) {\n    if (selection.getComposedRanges) {\n        let range = selection.getComposedRanges(view.root)[0];\n        if (range)\n            return buildSelectionRangeFromRange(view, range);\n    }\n    let found = null;\n    // Because Safari (at least in 2018-2021) doesn't provide regular\n    // access to the selection inside a shadowroot, we have to perform a\n    // ridiculous hack to get at it—using `execCommand` to trigger a\n    // `beforeInput` event so that we can read the target range from the\n    // event.\n    function read(event) {\n        event.preventDefault();\n        event.stopImmediatePropagation();\n        found = event.getTargetRanges()[0];\n    }\n    view.contentDOM.addEventListener(\"beforeinput\", read, true);\n    view.dom.ownerDocument.execCommand(\"indent\");\n    view.contentDOM.removeEventListener(\"beforeinput\", read, true);\n    return found ? buildSelectionRangeFromRange(view, found) : null;\n}\nclass EditContextManager {\n    constructor(view) {\n        // The document window for which the text in the context is\n        // maintained. For large documents, this may be smaller than the\n        // editor document. This window always includes the selection head.\n        this.from = 0;\n        this.to = 0;\n        // When applying a transaction, this is used to compare the change\n        // made to the context content to the change in the transaction in\n        // order to make the minimal changes to the context (since touching\n        // that sometimes breaks series of multiple edits made for a single\n        // user action on some Android keyboards)\n        this.pendingContextChange = null;\n        this.resetRange(view.state);\n        let context = this.editContext = new window.EditContext({\n            text: view.state.doc.sliceString(this.from, this.to),\n            selectionStart: this.toContextPos(Math.max(this.from, Math.min(this.to, view.state.selection.main.anchor))),\n            selectionEnd: this.toContextPos(view.state.selection.main.head)\n        });\n        context.addEventListener(\"textupdate\", e => {\n            let { anchor } = view.state.selection.main;\n            let change = { from: this.toEditorPos(e.updateRangeStart),\n                to: this.toEditorPos(e.updateRangeEnd),\n                insert: _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.Text.of(e.text.split(\"\\n\")) };\n            // If the window doesn't include the anchor, assume changes\n            // adjacent to a side go up to the anchor.\n            if (change.from == this.from && anchor < this.from)\n                change.from = anchor;\n            else if (change.to == this.to && anchor > this.to)\n                change.to = anchor;\n            // Edit context sometimes fire empty changes\n            if (change.from == change.to && !change.insert.length)\n                return;\n            this.pendingContextChange = change;\n            applyDOMChangeInner(view, change, _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.EditorSelection.single(this.toEditorPos(e.selectionStart), this.toEditorPos(e.selectionEnd)));\n            // If the transaction didn't flush our change, revert it so\n            // that the context is in sync with the editor state again.\n            if (this.pendingContextChange)\n                this.revertPending(view.state);\n        });\n        context.addEventListener(\"characterboundsupdate\", e => {\n            let rects = [], prev = null;\n            for (let i = this.toEditorPos(e.rangeStart), end = this.toEditorPos(e.rangeEnd); i < end; i++) {\n                let rect = view.coordsForChar(i);\n                prev = (rect && new DOMRect(rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top))\n                    || prev || new DOMRect;\n                rects.push(prev);\n            }\n            context.updateCharacterBounds(e.rangeStart, rects);\n        });\n        context.addEventListener(\"textformatupdate\", e => {\n            let deco = [];\n            for (let format of e.getTextFormats()) {\n                let lineStyle = format.underlineStyle, thickness = format.underlineThickness;\n                if (lineStyle != \"None\" && thickness != \"None\") {\n                    let style = `text-decoration: underline ${lineStyle == \"Dashed\" ? \"dashed \" : lineStyle == \"Squiggle\" ? \"wavy \" : \"\"}${thickness == \"Thin\" ? 1 : 2}px`;\n                    deco.push(Decoration.mark({ attributes: { style } })\n                        .range(this.toEditorPos(format.rangeStart), this.toEditorPos(format.rangeEnd)));\n                }\n            }\n            view.dispatch({ effects: setEditContextFormatting.of(Decoration.set(deco)) });\n        });\n        context.addEventListener(\"compositionstart\", () => {\n            if (view.inputState.composing < 0) {\n                view.inputState.composing = 0;\n                view.inputState.compositionFirstChange = true;\n            }\n        });\n        context.addEventListener(\"compositionend\", () => {\n            view.inputState.composing = -1;\n            view.inputState.compositionFirstChange = null;\n        });\n        this.measureReq = { read: view => {\n                this.editContext.updateControlBounds(view.contentDOM.getBoundingClientRect());\n                let sel = getSelection(view.root);\n                if (sel && sel.rangeCount)\n                    this.editContext.updateSelectionBounds(sel.getRangeAt(0).getBoundingClientRect());\n            } };\n    }\n    applyEdits(update) {\n        let off = 0, abort = false, pending = this.pendingContextChange;\n        update.changes.iterChanges((fromA, toA, _fromB, _toB, insert) => {\n            if (abort)\n                return;\n            let dLen = insert.length - (toA - fromA);\n            if (pending && toA >= pending.to) {\n                if (pending.from == fromA && pending.to == toA && pending.insert.eq(insert)) {\n                    pending = this.pendingContextChange = null; // Match\n                    off += dLen;\n                    return;\n                }\n                else { // Mismatch, revert\n                    pending = null;\n                    this.revertPending(update.state);\n                }\n            }\n            fromA += off;\n            toA += off;\n            if (toA <= this.from) { // Before the window\n                this.from += dLen;\n                this.to += dLen;\n            }\n            else if (fromA < this.to) { // Overlaps with window\n                if (fromA < this.from || toA > this.to || (this.to - this.from) + insert.length > 30000 /* CxVp.MaxSize */) {\n                    abort = true;\n                    return;\n                }\n                this.editContext.updateText(this.toContextPos(fromA), this.toContextPos(toA), insert.toString());\n                this.to += dLen;\n            }\n            off += dLen;\n        });\n        if (pending && !abort)\n            this.revertPending(update.state);\n        return !abort;\n    }\n    update(update) {\n        if (!this.applyEdits(update) || !this.rangeIsValid(update.state)) {\n            this.pendingContextChange = null;\n            this.resetRange(update.state);\n            this.editContext.updateText(0, this.editContext.text.length, update.state.doc.sliceString(this.from, this.to));\n            this.setSelection(update.state);\n        }\n        else if (update.docChanged || update.selectionSet) {\n            this.setSelection(update.state);\n        }\n        if (update.geometryChanged || update.docChanged || update.selectionSet)\n            update.view.requestMeasure(this.measureReq);\n    }\n    resetRange(state) {\n        let { head } = state.selection.main;\n        this.from = Math.max(0, head - 10000 /* CxVp.Margin */);\n        this.to = Math.min(state.doc.length, head + 10000 /* CxVp.Margin */);\n    }\n    revertPending(state) {\n        let pending = this.pendingContextChange;\n        this.pendingContextChange = null;\n        this.editContext.updateText(this.toContextPos(pending.from), this.toContextPos(pending.to + pending.insert.length), state.doc.sliceString(pending.from, pending.to));\n    }\n    setSelection(state) {\n        let { main } = state.selection;\n        let start = this.toContextPos(Math.max(this.from, Math.min(this.to, main.anchor)));\n        let end = this.toContextPos(main.head);\n        if (this.editContext.selectionStart != start || this.editContext.selectionEnd != end)\n            this.editContext.updateSelection(start, end);\n    }\n    rangeIsValid(state) {\n        let { head } = state.selection.main;\n        return !(this.from > 0 && head - this.from < 500 /* CxVp.MinMargin */ ||\n            this.to < state.doc.length && this.to - head < 500 /* CxVp.MinMargin */ ||\n            this.to - this.from > 10000 /* CxVp.Margin */ * 3);\n    }\n    toEditorPos(contextPos) { return contextPos + this.from; }\n    toContextPos(editorPos) { return editorPos - this.from; }\n}\n\n// The editor's update state machine looks something like this:\n//\n//     Idle → Updating ⇆ Idle (unchecked) → Measuring → Idle\n//                                         ↑      ↓\n//                                         Updating (measure)\n//\n// The difference between 'Idle' and 'Idle (unchecked)' lies in\n// whether a layout check has been scheduled. A regular update through\n// the `update` method updates the DOM in a write-only fashion, and\n// relies on a check (scheduled with `requestAnimationFrame`) to make\n// sure everything is where it should be and the viewport covers the\n// visible code. That check continues to measure and then optionally\n// update until it reaches a coherent state.\n/**\nAn editor view represents the editor's user interface. It holds\nthe editable DOM surface, and possibly other elements such as the\nline number gutter. It handles events and dispatches state\ntransactions for editing actions.\n*/\nclass EditorView {\n    /**\n    The current editor state.\n    */\n    get state() { return this.viewState.state; }\n    /**\n    To be able to display large documents without consuming too much\n    memory or overloading the browser, CodeMirror only draws the\n    code that is visible (plus a margin around it) to the DOM. This\n    property tells you the extent of the current drawn viewport, in\n    document positions.\n    */\n    get viewport() { return this.viewState.viewport; }\n    /**\n    When there are, for example, large collapsed ranges in the\n    viewport, its size can be a lot bigger than the actual visible\n    content. Thus, if you are doing something like styling the\n    content in the viewport, it is preferable to only do so for\n    these ranges, which are the subset of the viewport that is\n    actually drawn.\n    */\n    get visibleRanges() { return this.viewState.visibleRanges; }\n    /**\n    Returns false when the editor is entirely scrolled out of view\n    or otherwise hidden.\n    */\n    get inView() { return this.viewState.inView; }\n    /**\n    Indicates whether the user is currently composing text via\n    [IME](https://en.wikipedia.org/wiki/Input_method), and at least\n    one change has been made in the current composition.\n    */\n    get composing() { return this.inputState.composing > 0; }\n    /**\n    Indicates whether the user is currently in composing state. Note\n    that on some platforms, like Android, this will be the case a\n    lot, since just putting the cursor on a word starts a\n    composition there.\n    */\n    get compositionStarted() { return this.inputState.composing >= 0; }\n    /**\n    The document or shadow root that the view lives in.\n    */\n    get root() { return this._root; }\n    /**\n    @internal\n    */\n    get win() { return this.dom.ownerDocument.defaultView || window; }\n    /**\n    Construct a new view. You'll want to either provide a `parent`\n    option, or put `view.dom` into your document after creating a\n    view, so that the user can see the editor.\n    */\n    constructor(config = {}) {\n        this.plugins = [];\n        this.pluginMap = new Map;\n        this.editorAttrs = {};\n        this.contentAttrs = {};\n        this.bidiCache = [];\n        this.destroyed = false;\n        /**\n        @internal\n        */\n        this.updateState = 2 /* UpdateState.Updating */;\n        /**\n        @internal\n        */\n        this.measureScheduled = -1;\n        /**\n        @internal\n        */\n        this.measureRequests = [];\n        this.contentDOM = document.createElement(\"div\");\n        this.scrollDOM = document.createElement(\"div\");\n        this.scrollDOM.tabIndex = -1;\n        this.scrollDOM.className = \"cm-scroller\";\n        this.scrollDOM.appendChild(this.contentDOM);\n        this.announceDOM = document.createElement(\"div\");\n        this.announceDOM.className = \"cm-announced\";\n        this.announceDOM.setAttribute(\"aria-live\", \"polite\");\n        this.dom = document.createElement(\"div\");\n        this.dom.appendChild(this.announceDOM);\n        this.dom.appendChild(this.scrollDOM);\n        if (config.parent)\n            config.parent.appendChild(this.dom);\n        let { dispatch } = config;\n        this.dispatchTransactions = config.dispatchTransactions ||\n            (dispatch && ((trs) => trs.forEach(tr => dispatch(tr, this)))) ||\n            ((trs) => this.update(trs));\n        this.dispatch = this.dispatch.bind(this);\n        this._root = (config.root || getRoot(config.parent) || document);\n        this.viewState = new ViewState(config.state || _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.EditorState.create(config));\n        if (config.scrollTo && config.scrollTo.is(scrollIntoView))\n            this.viewState.scrollTarget = config.scrollTo.value.clip(this.viewState.state);\n        this.plugins = this.state.facet(viewPlugin).map(spec => new PluginInstance(spec));\n        for (let plugin of this.plugins)\n            plugin.update(this);\n        this.observer = new DOMObserver(this);\n        this.inputState = new InputState(this);\n        this.inputState.ensureHandlers(this.plugins);\n        this.docView = new DocView(this);\n        this.mountStyles();\n        this.updateAttrs();\n        this.updateState = 0 /* UpdateState.Idle */;\n        this.requestMeasure();\n    }\n    dispatch(...input) {\n        let trs = input.length == 1 && input[0] instanceof _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.Transaction ? input\n            : input.length == 1 && Array.isArray(input[0]) ? input[0]\n                : [this.state.update(...input)];\n        this.dispatchTransactions(trs, this);\n    }\n    /**\n    Update the view for the given array of transactions. This will\n    update the visible document and selection to match the state\n    produced by the transactions, and notify view plugins of the\n    change. You should usually call\n    [`dispatch`](https://codemirror.net/6/docs/ref/#view.EditorView.dispatch) instead, which uses this\n    as a primitive.\n    */\n    update(transactions) {\n        if (this.updateState != 0 /* UpdateState.Idle */)\n            throw new Error(\"Calls to EditorView.update are not allowed while an update is in progress\");\n        let redrawn = false, attrsChanged = false, update;\n        let state = this.state;\n        for (let tr of transactions) {\n            if (tr.startState != state)\n                throw new RangeError(\"Trying to update state with a transaction that doesn't start from the previous state.\");\n            state = tr.state;\n        }\n        if (this.destroyed) {\n            this.viewState.state = state;\n            return;\n        }\n        let focus = this.hasFocus, focusFlag = 0, dispatchFocus = null;\n        if (transactions.some(tr => tr.annotation(isFocusChange))) {\n            this.inputState.notifiedFocused = focus;\n            // If a focus-change transaction is being dispatched, set this update flag.\n            focusFlag = 1 /* UpdateFlag.Focus */;\n        }\n        else if (focus != this.inputState.notifiedFocused) {\n            this.inputState.notifiedFocused = focus;\n            // Schedule a separate focus transaction if necessary, otherwise\n            // add a flag to this update\n            dispatchFocus = focusChangeTransaction(state, focus);\n            if (!dispatchFocus)\n                focusFlag = 1 /* UpdateFlag.Focus */;\n        }\n        // If there was a pending DOM change, eagerly read it and try to\n        // apply it after the given transactions.\n        let pendingKey = this.observer.delayedAndroidKey, domChange = null;\n        if (pendingKey) {\n            this.observer.clearDelayedAndroidKey();\n            domChange = this.observer.readChange();\n            // Only try to apply DOM changes if the transactions didn't\n            // change the doc or selection.\n            if (domChange && !this.state.doc.eq(state.doc) || !this.state.selection.eq(state.selection))\n                domChange = null;\n        }\n        else {\n            this.observer.clear();\n        }\n        // When the phrases change, redraw the editor\n        if (state.facet(_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.EditorState.phrases) != this.state.facet(_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.EditorState.phrases))\n            return this.setState(state);\n        update = ViewUpdate.create(this, state, transactions);\n        update.flags |= focusFlag;\n        let scrollTarget = this.viewState.scrollTarget;\n        try {\n            this.updateState = 2 /* UpdateState.Updating */;\n            for (let tr of transactions) {\n                if (scrollTarget)\n                    scrollTarget = scrollTarget.map(tr.changes);\n                if (tr.scrollIntoView) {\n                    let { main } = tr.state.selection;\n                    scrollTarget = new ScrollTarget(main.empty ? main : _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.EditorSelection.cursor(main.head, main.head > main.anchor ? -1 : 1));\n                }\n                for (let e of tr.effects)\n                    if (e.is(scrollIntoView))\n                        scrollTarget = e.value.clip(this.state);\n            }\n            this.viewState.update(update, scrollTarget);\n            this.bidiCache = CachedOrder.update(this.bidiCache, update.changes);\n            if (!update.empty) {\n                this.updatePlugins(update);\n                this.inputState.update(update);\n            }\n            redrawn = this.docView.update(update);\n            if (this.state.facet(styleModule) != this.styleModules)\n                this.mountStyles();\n            attrsChanged = this.updateAttrs();\n            this.showAnnouncements(transactions);\n            this.docView.updateSelection(redrawn, transactions.some(tr => tr.isUserEvent(\"select.pointer\")));\n        }\n        finally {\n            this.updateState = 0 /* UpdateState.Idle */;\n        }\n        if (update.startState.facet(theme) != update.state.facet(theme))\n            this.viewState.mustMeasureContent = true;\n        if (redrawn || attrsChanged || scrollTarget || this.viewState.mustEnforceCursorAssoc || this.viewState.mustMeasureContent)\n            this.requestMeasure();\n        if (redrawn)\n            this.docViewUpdate();\n        if (!update.empty)\n            for (let listener of this.state.facet(updateListener)) {\n                try {\n                    listener(update);\n                }\n                catch (e) {\n                    logException(this.state, e, \"update listener\");\n                }\n            }\n        if (dispatchFocus || domChange)\n            Promise.resolve().then(() => {\n                if (dispatchFocus && this.state == dispatchFocus.startState)\n                    this.dispatch(dispatchFocus);\n                if (domChange) {\n                    if (!applyDOMChange(this, domChange) && pendingKey.force)\n                        dispatchKey(this.contentDOM, pendingKey.key, pendingKey.keyCode);\n                }\n            });\n    }\n    /**\n    Reset the view to the given state. (This will cause the entire\n    document to be redrawn and all view plugins to be reinitialized,\n    so you should probably only use it when the new state isn't\n    derived from the old state. Otherwise, use\n    [`dispatch`](https://codemirror.net/6/docs/ref/#view.EditorView.dispatch) instead.)\n    */\n    setState(newState) {\n        if (this.updateState != 0 /* UpdateState.Idle */)\n            throw new Error(\"Calls to EditorView.setState are not allowed while an update is in progress\");\n        if (this.destroyed) {\n            this.viewState.state = newState;\n            return;\n        }\n        this.updateState = 2 /* UpdateState.Updating */;\n        let hadFocus = this.hasFocus;\n        try {\n            for (let plugin of this.plugins)\n                plugin.destroy(this);\n            this.viewState = new ViewState(newState);\n            this.plugins = newState.facet(viewPlugin).map(spec => new PluginInstance(spec));\n            this.pluginMap.clear();\n            for (let plugin of this.plugins)\n                plugin.update(this);\n            this.docView.destroy();\n            this.docView = new DocView(this);\n            this.inputState.ensureHandlers(this.plugins);\n            this.mountStyles();\n            this.updateAttrs();\n            this.bidiCache = [];\n        }\n        finally {\n            this.updateState = 0 /* UpdateState.Idle */;\n        }\n        if (hadFocus)\n            this.focus();\n        this.requestMeasure();\n    }\n    updatePlugins(update) {\n        let prevSpecs = update.startState.facet(viewPlugin), specs = update.state.facet(viewPlugin);\n        if (prevSpecs != specs) {\n            let newPlugins = [];\n            for (let spec of specs) {\n                let found = prevSpecs.indexOf(spec);\n                if (found < 0) {\n                    newPlugins.push(new PluginInstance(spec));\n                }\n                else {\n                    let plugin = this.plugins[found];\n                    plugin.mustUpdate = update;\n                    newPlugins.push(plugin);\n                }\n            }\n            for (let plugin of this.plugins)\n                if (plugin.mustUpdate != update)\n                    plugin.destroy(this);\n            this.plugins = newPlugins;\n            this.pluginMap.clear();\n        }\n        else {\n            for (let p of this.plugins)\n                p.mustUpdate = update;\n        }\n        for (let i = 0; i < this.plugins.length; i++)\n            this.plugins[i].update(this);\n        if (prevSpecs != specs)\n            this.inputState.ensureHandlers(this.plugins);\n    }\n    docViewUpdate() {\n        for (let plugin of this.plugins) {\n            let val = plugin.value;\n            if (val && val.docViewUpdate) {\n                try {\n                    val.docViewUpdate(this);\n                }\n                catch (e) {\n                    logException(this.state, e, \"doc view update listener\");\n                }\n            }\n        }\n    }\n    /**\n    @internal\n    */\n    measure(flush = true) {\n        if (this.destroyed)\n            return;\n        if (this.measureScheduled > -1)\n            this.win.cancelAnimationFrame(this.measureScheduled);\n        if (this.observer.delayedAndroidKey) {\n            this.measureScheduled = -1;\n            this.requestMeasure();\n            return;\n        }\n        this.measureScheduled = 0; // Prevent requestMeasure calls from scheduling another animation frame\n        if (flush)\n            this.observer.forceFlush();\n        let updated = null;\n        let sDOM = this.scrollDOM, scrollTop = sDOM.scrollTop * this.scaleY;\n        let { scrollAnchorPos, scrollAnchorHeight } = this.viewState;\n        if (Math.abs(scrollTop - this.viewState.scrollTop) > 1)\n            scrollAnchorHeight = -1;\n        this.viewState.scrollAnchorHeight = -1;\n        try {\n            for (let i = 0;; i++) {\n                if (scrollAnchorHeight < 0) {\n                    if (isScrolledToBottom(sDOM)) {\n                        scrollAnchorPos = -1;\n                        scrollAnchorHeight = this.viewState.heightMap.height;\n                    }\n                    else {\n                        let block = this.viewState.scrollAnchorAt(scrollTop);\n                        scrollAnchorPos = block.from;\n                        scrollAnchorHeight = block.top;\n                    }\n                }\n                this.updateState = 1 /* UpdateState.Measuring */;\n                let changed = this.viewState.measure(this);\n                if (!changed && !this.measureRequests.length && this.viewState.scrollTarget == null)\n                    break;\n                if (i > 5) {\n                    console.warn(this.measureRequests.length\n                        ? \"Measure loop restarted more than 5 times\"\n                        : \"Viewport failed to stabilize\");\n                    break;\n                }\n                let measuring = [];\n                // Only run measure requests in this cycle when the viewport didn't change\n                if (!(changed & 4 /* UpdateFlag.Viewport */))\n                    [this.measureRequests, measuring] = [measuring, this.measureRequests];\n                let measured = measuring.map(m => {\n                    try {\n                        return m.read(this);\n                    }\n                    catch (e) {\n                        logException(this.state, e);\n                        return BadMeasure;\n                    }\n                });\n                let update = ViewUpdate.create(this, this.state, []), redrawn = false;\n                update.flags |= changed;\n                if (!updated)\n                    updated = update;\n                else\n                    updated.flags |= changed;\n                this.updateState = 2 /* UpdateState.Updating */;\n                if (!update.empty) {\n                    this.updatePlugins(update);\n                    this.inputState.update(update);\n                    this.updateAttrs();\n                    redrawn = this.docView.update(update);\n                    if (redrawn)\n                        this.docViewUpdate();\n                }\n                for (let i = 0; i < measuring.length; i++)\n                    if (measured[i] != BadMeasure) {\n                        try {\n                            let m = measuring[i];\n                            if (m.write)\n                                m.write(measured[i], this);\n                        }\n                        catch (e) {\n                            logException(this.state, e);\n                        }\n                    }\n                if (redrawn)\n                    this.docView.updateSelection(true);\n                if (!update.viewportChanged && this.measureRequests.length == 0) {\n                    if (this.viewState.editorHeight) {\n                        if (this.viewState.scrollTarget) {\n                            this.docView.scrollIntoView(this.viewState.scrollTarget);\n                            this.viewState.scrollTarget = null;\n                            scrollAnchorHeight = -1;\n                            continue;\n                        }\n                        else {\n                            let newAnchorHeight = scrollAnchorPos < 0 ? this.viewState.heightMap.height :\n                                this.viewState.lineBlockAt(scrollAnchorPos).top;\n                            let diff = newAnchorHeight - scrollAnchorHeight;\n                            if (diff > 1 || diff < -1) {\n                                scrollTop = scrollTop + diff;\n                                sDOM.scrollTop = scrollTop / this.scaleY;\n                                scrollAnchorHeight = -1;\n                                continue;\n                            }\n                        }\n                    }\n                    break;\n                }\n            }\n        }\n        finally {\n            this.updateState = 0 /* UpdateState.Idle */;\n            this.measureScheduled = -1;\n        }\n        if (updated && !updated.empty)\n            for (let listener of this.state.facet(updateListener))\n                listener(updated);\n    }\n    /**\n    Get the CSS classes for the currently active editor themes.\n    */\n    get themeClasses() {\n        return baseThemeID + \" \" +\n            (this.state.facet(darkTheme) ? baseDarkID : baseLightID) + \" \" +\n            this.state.facet(theme);\n    }\n    updateAttrs() {\n        let editorAttrs = attrsFromFacet(this, editorAttributes, {\n            class: \"cm-editor\" + (this.hasFocus ? \" cm-focused \" : \" \") + this.themeClasses\n        });\n        let contentAttrs = {\n            spellcheck: \"false\",\n            autocorrect: \"off\",\n            autocapitalize: \"off\",\n            translate: \"no\",\n            contenteditable: !this.state.facet(editable) ? \"false\" : \"true\",\n            class: \"cm-content\",\n            style: `${browser.tabSize}: ${this.state.tabSize}`,\n            role: \"textbox\",\n            \"aria-multiline\": \"true\"\n        };\n        if (this.state.readOnly)\n            contentAttrs[\"aria-readonly\"] = \"true\";\n        attrsFromFacet(this, contentAttributes, contentAttrs);\n        let changed = this.observer.ignore(() => {\n            let changedContent = updateAttrs(this.contentDOM, this.contentAttrs, contentAttrs);\n            let changedEditor = updateAttrs(this.dom, this.editorAttrs, editorAttrs);\n            return changedContent || changedEditor;\n        });\n        this.editorAttrs = editorAttrs;\n        this.contentAttrs = contentAttrs;\n        return changed;\n    }\n    showAnnouncements(trs) {\n        let first = true;\n        for (let tr of trs)\n            for (let effect of tr.effects)\n                if (effect.is(EditorView.announce)) {\n                    if (first)\n                        this.announceDOM.textContent = \"\";\n                    first = false;\n                    let div = this.announceDOM.appendChild(document.createElement(\"div\"));\n                    div.textContent = effect.value;\n                }\n    }\n    mountStyles() {\n        this.styleModules = this.state.facet(styleModule);\n        let nonce = this.state.facet(EditorView.cspNonce);\n        style_mod__WEBPACK_IMPORTED_MODULE_0__.StyleModule.mount(this.root, this.styleModules.concat(baseTheme$1).reverse(), nonce ? { nonce } : undefined);\n    }\n    readMeasured() {\n        if (this.updateState == 2 /* UpdateState.Updating */)\n            throw new Error(\"Reading the editor layout isn't allowed during an update\");\n        if (this.updateState == 0 /* UpdateState.Idle */ && this.measureScheduled > -1)\n            this.measure(false);\n    }\n    /**\n    Schedule a layout measurement, optionally providing callbacks to\n    do custom DOM measuring followed by a DOM write phase. Using\n    this is preferable reading DOM layout directly from, for\n    example, an event handler, because it'll make sure measuring and\n    drawing done by other components is synchronized, avoiding\n    unnecessary DOM layout computations.\n    */\n    requestMeasure(request) {\n        if (this.measureScheduled < 0)\n            this.measureScheduled = this.win.requestAnimationFrame(() => this.measure());\n        if (request) {\n            if (this.measureRequests.indexOf(request) > -1)\n                return;\n            if (request.key != null)\n                for (let i = 0; i < this.measureRequests.length; i++) {\n                    if (this.measureRequests[i].key === request.key) {\n                        this.measureRequests[i] = request;\n                        return;\n                    }\n                }\n            this.measureRequests.push(request);\n        }\n    }\n    /**\n    Get the value of a specific plugin, if present. Note that\n    plugins that crash can be dropped from a view, so even when you\n    know you registered a given plugin, it is recommended to check\n    the return value of this method.\n    */\n    plugin(plugin) {\n        let known = this.pluginMap.get(plugin);\n        if (known === undefined || known && known.spec != plugin)\n            this.pluginMap.set(plugin, known = this.plugins.find(p => p.spec == plugin) || null);\n        return known && known.update(this).value;\n    }\n    /**\n    The top position of the document, in screen coordinates. This\n    may be negative when the editor is scrolled down. Points\n    directly to the top of the first line, not above the padding.\n    */\n    get documentTop() {\n        return this.contentDOM.getBoundingClientRect().top + this.viewState.paddingTop;\n    }\n    /**\n    Reports the padding above and below the document.\n    */\n    get documentPadding() {\n        return { top: this.viewState.paddingTop, bottom: this.viewState.paddingBottom };\n    }\n    /**\n    If the editor is transformed with CSS, this provides the scale\n    along the X axis. Otherwise, it will just be 1. Note that\n    transforms other than translation and scaling are not supported.\n    */\n    get scaleX() { return this.viewState.scaleX; }\n    /**\n    Provide the CSS transformed scale along the Y axis.\n    */\n    get scaleY() { return this.viewState.scaleY; }\n    /**\n    Find the text line or block widget at the given vertical\n    position (which is interpreted as relative to the [top of the\n    document](https://codemirror.net/6/docs/ref/#view.EditorView.documentTop)).\n    */\n    elementAtHeight(height) {\n        this.readMeasured();\n        return this.viewState.elementAtHeight(height);\n    }\n    /**\n    Find the line block (see\n    [`lineBlockAt`](https://codemirror.net/6/docs/ref/#view.EditorView.lineBlockAt) at the given\n    height, again interpreted relative to the [top of the\n    document](https://codemirror.net/6/docs/ref/#view.EditorView.documentTop).\n    */\n    lineBlockAtHeight(height) {\n        this.readMeasured();\n        return this.viewState.lineBlockAtHeight(height);\n    }\n    /**\n    Get the extent and vertical position of all [line\n    blocks](https://codemirror.net/6/docs/ref/#view.EditorView.lineBlockAt) in the viewport. Positions\n    are relative to the [top of the\n    document](https://codemirror.net/6/docs/ref/#view.EditorView.documentTop);\n    */\n    get viewportLineBlocks() {\n        return this.viewState.viewportLines;\n    }\n    /**\n    Find the line block around the given document position. A line\n    block is a range delimited on both sides by either a\n    non-[hidden](https://codemirror.net/6/docs/ref/#view.Decoration^replace) line breaks, or the\n    start/end of the document. It will usually just hold a line of\n    text, but may be broken into multiple textblocks by block\n    widgets.\n    */\n    lineBlockAt(pos) {\n        return this.viewState.lineBlockAt(pos);\n    }\n    /**\n    The editor's total content height.\n    */\n    get contentHeight() {\n        return this.viewState.contentHeight;\n    }\n    /**\n    Move a cursor position by [grapheme\n    cluster](https://codemirror.net/6/docs/ref/#state.findClusterBreak). `forward` determines whether\n    the motion is away from the line start, or towards it. In\n    bidirectional text, the line is traversed in visual order, using\n    the editor's [text direction](https://codemirror.net/6/docs/ref/#view.EditorView.textDirection).\n    When the start position was the last one on the line, the\n    returned position will be across the line break. If there is no\n    further line, the original position is returned.\n    \n    By default, this method moves over a single cluster. The\n    optional `by` argument can be used to move across more. It will\n    be called with the first cluster as argument, and should return\n    a predicate that determines, for each subsequent cluster,\n    whether it should also be moved over.\n    */\n    moveByChar(start, forward, by) {\n        return skipAtoms(this, start, moveByChar(this, start, forward, by));\n    }\n    /**\n    Move a cursor position across the next group of either\n    [letters](https://codemirror.net/6/docs/ref/#state.EditorState.charCategorizer) or non-letter\n    non-whitespace characters.\n    */\n    moveByGroup(start, forward) {\n        return skipAtoms(this, start, moveByChar(this, start, forward, initial => byGroup(this, start.head, initial)));\n    }\n    /**\n    Get the cursor position visually at the start or end of a line.\n    Note that this may differ from the _logical_ position at its\n    start or end (which is simply at `line.from`/`line.to`) if text\n    at the start or end goes against the line's base text direction.\n    */\n    visualLineSide(line, end) {\n        let order = this.bidiSpans(line), dir = this.textDirectionAt(line.from);\n        let span = order[end ? order.length - 1 : 0];\n        return _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.EditorSelection.cursor(span.side(end, dir) + line.from, span.forward(!end, dir) ? 1 : -1);\n    }\n    /**\n    Move to the next line boundary in the given direction. If\n    `includeWrap` is true, line wrapping is on, and there is a\n    further wrap point on the current line, the wrap point will be\n    returned. Otherwise this function will return the start or end\n    of the line.\n    */\n    moveToLineBoundary(start, forward, includeWrap = true) {\n        return moveToLineBoundary(this, start, forward, includeWrap);\n    }\n    /**\n    Move a cursor position vertically. When `distance` isn't given,\n    it defaults to moving to the next line (including wrapped\n    lines). Otherwise, `distance` should provide a positive distance\n    in pixels.\n    \n    When `start` has a\n    [`goalColumn`](https://codemirror.net/6/docs/ref/#state.SelectionRange.goalColumn), the vertical\n    motion will use that as a target horizontal position. Otherwise,\n    the cursor's own horizontal position is used. The returned\n    cursor will have its goal column set to whichever column was\n    used.\n    */\n    moveVertically(start, forward, distance) {\n        return skipAtoms(this, start, moveVertically(this, start, forward, distance));\n    }\n    /**\n    Find the DOM parent node and offset (child offset if `node` is\n    an element, character offset when it is a text node) at the\n    given document position.\n    \n    Note that for positions that aren't currently in\n    `visibleRanges`, the resulting DOM position isn't necessarily\n    meaningful (it may just point before or after a placeholder\n    element).\n    */\n    domAtPos(pos) {\n        return this.docView.domAtPos(pos);\n    }\n    /**\n    Find the document position at the given DOM node. Can be useful\n    for associating positions with DOM events. Will raise an error\n    when `node` isn't part of the editor content.\n    */\n    posAtDOM(node, offset = 0) {\n        return this.docView.posFromDOM(node, offset);\n    }\n    posAtCoords(coords, precise = true) {\n        this.readMeasured();\n        return posAtCoords(this, coords, precise);\n    }\n    /**\n    Get the screen coordinates at the given document position.\n    `side` determines whether the coordinates are based on the\n    element before (-1) or after (1) the position (if no element is\n    available on the given side, the method will transparently use\n    another strategy to get reasonable coordinates).\n    */\n    coordsAtPos(pos, side = 1) {\n        this.readMeasured();\n        let rect = this.docView.coordsAt(pos, side);\n        if (!rect || rect.left == rect.right)\n            return rect;\n        let line = this.state.doc.lineAt(pos), order = this.bidiSpans(line);\n        let span = order[BidiSpan.find(order, pos - line.from, -1, side)];\n        return flattenRect(rect, (span.dir == Direction.LTR) == (side > 0));\n    }\n    /**\n    Return the rectangle around a given character. If `pos` does not\n    point in front of a character that is in the viewport and\n    rendered (i.e. not replaced, not a line break), this will return\n    null. For space characters that are a line wrap point, this will\n    return the position before the line break.\n    */\n    coordsForChar(pos) {\n        this.readMeasured();\n        return this.docView.coordsForChar(pos);\n    }\n    /**\n    The default width of a character in the editor. May not\n    accurately reflect the width of all characters (given variable\n    width fonts or styling of invididual ranges).\n    */\n    get defaultCharacterWidth() { return this.viewState.heightOracle.charWidth; }\n    /**\n    The default height of a line in the editor. May not be accurate\n    for all lines.\n    */\n    get defaultLineHeight() { return this.viewState.heightOracle.lineHeight; }\n    /**\n    The text direction\n    ([`direction`](https://developer.mozilla.org/en-US/docs/Web/CSS/direction)\n    CSS property) of the editor's content element.\n    */\n    get textDirection() { return this.viewState.defaultTextDirection; }\n    /**\n    Find the text direction of the block at the given position, as\n    assigned by CSS. If\n    [`perLineTextDirection`](https://codemirror.net/6/docs/ref/#view.EditorView^perLineTextDirection)\n    isn't enabled, or the given position is outside of the viewport,\n    this will always return the same as\n    [`textDirection`](https://codemirror.net/6/docs/ref/#view.EditorView.textDirection). Note that\n    this may trigger a DOM layout.\n    */\n    textDirectionAt(pos) {\n        let perLine = this.state.facet(perLineTextDirection);\n        if (!perLine || pos < this.viewport.from || pos > this.viewport.to)\n            return this.textDirection;\n        this.readMeasured();\n        return this.docView.textDirectionAt(pos);\n    }\n    /**\n    Whether this editor [wraps lines](https://codemirror.net/6/docs/ref/#view.EditorView.lineWrapping)\n    (as determined by the\n    [`white-space`](https://developer.mozilla.org/en-US/docs/Web/CSS/white-space)\n    CSS property of its content element).\n    */\n    get lineWrapping() { return this.viewState.heightOracle.lineWrapping; }\n    /**\n    Returns the bidirectional text structure of the given line\n    (which should be in the current document) as an array of span\n    objects. The order of these spans matches the [text\n    direction](https://codemirror.net/6/docs/ref/#view.EditorView.textDirection)—if that is\n    left-to-right, the leftmost spans come first, otherwise the\n    rightmost spans come first.\n    */\n    bidiSpans(line) {\n        if (line.length > MaxBidiLine)\n            return trivialOrder(line.length);\n        let dir = this.textDirectionAt(line.from), isolates;\n        for (let entry of this.bidiCache) {\n            if (entry.from == line.from && entry.dir == dir &&\n                (entry.fresh || isolatesEq(entry.isolates, isolates = getIsolatedRanges(this, line))))\n                return entry.order;\n        }\n        if (!isolates)\n            isolates = getIsolatedRanges(this, line);\n        let order = computeOrder(line.text, dir, isolates);\n        this.bidiCache.push(new CachedOrder(line.from, line.to, dir, isolates, true, order));\n        return order;\n    }\n    /**\n    Check whether the editor has focus.\n    */\n    get hasFocus() {\n        var _a;\n        // Safari return false for hasFocus when the context menu is open\n        // or closing, which leads us to ignore selection changes from the\n        // context menu because it looks like the editor isn't focused.\n        // This kludges around that.\n        return (this.dom.ownerDocument.hasFocus() || browser.safari && ((_a = this.inputState) === null || _a === void 0 ? void 0 : _a.lastContextMenu) > Date.now() - 3e4) &&\n            this.root.activeElement == this.contentDOM;\n    }\n    /**\n    Put focus on the editor.\n    */\n    focus() {\n        this.observer.ignore(() => {\n            focusPreventScroll(this.contentDOM);\n            this.docView.updateSelection();\n        });\n    }\n    /**\n    Update the [root](https://codemirror.net/6/docs/ref/##view.EditorViewConfig.root) in which the editor lives. This is only\n    necessary when moving the editor's existing DOM to a new window or shadow root.\n    */\n    setRoot(root) {\n        if (this._root != root) {\n            this._root = root;\n            this.observer.setWindow((root.nodeType == 9 ? root : root.ownerDocument).defaultView || window);\n            this.mountStyles();\n        }\n    }\n    /**\n    Clean up this editor view, removing its element from the\n    document, unregistering event handlers, and notifying\n    plugins. The view instance can no longer be used after\n    calling this.\n    */\n    destroy() {\n        if (this.root.activeElement == this.contentDOM)\n            this.contentDOM.blur();\n        for (let plugin of this.plugins)\n            plugin.destroy(this);\n        this.plugins = [];\n        this.inputState.destroy();\n        this.docView.destroy();\n        this.dom.remove();\n        this.observer.destroy();\n        if (this.measureScheduled > -1)\n            this.win.cancelAnimationFrame(this.measureScheduled);\n        this.destroyed = true;\n    }\n    /**\n    Returns an effect that can be\n    [added](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) to a transaction to\n    cause it to scroll the given position or range into view.\n    */\n    static scrollIntoView(pos, options = {}) {\n        return scrollIntoView.of(new ScrollTarget(typeof pos == \"number\" ? _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.EditorSelection.cursor(pos) : pos, options.y, options.x, options.yMargin, options.xMargin));\n    }\n    /**\n    Return an effect that resets the editor to its current (at the\n    time this method was called) scroll position. Note that this\n    only affects the editor's own scrollable element, not parents.\n    See also\n    [`EditorViewConfig.scrollTo`](https://codemirror.net/6/docs/ref/#view.EditorViewConfig.scrollTo).\n    \n    The effect should be used with a document identical to the one\n    it was created for. Failing to do so is not an error, but may\n    not scroll to the expected position. You can\n    [map](https://codemirror.net/6/docs/ref/#state.StateEffect.map) the effect to account for changes.\n    */\n    scrollSnapshot() {\n        let { scrollTop, scrollLeft } = this.scrollDOM;\n        let ref = this.viewState.scrollAnchorAt(scrollTop);\n        return scrollIntoView.of(new ScrollTarget(_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.EditorSelection.cursor(ref.from), \"start\", \"start\", ref.top - scrollTop, scrollLeft, true));\n    }\n    /**\n    Enable or disable tab-focus mode, which disables key bindings\n    for Tab and Shift-Tab, letting the browser's default\n    focus-changing behavior go through instead. This is useful to\n    prevent trapping keyboard users in your editor.\n    \n    Without argument, this toggles the mode. With a boolean, it\n    enables (true) or disables it (false). Given a number, it\n    temporarily enables the mode until that number of milliseconds\n    have passed or another non-Tab key is pressed.\n    */\n    setTabFocusMode(to) {\n        if (to == null)\n            this.inputState.tabFocusMode = this.inputState.tabFocusMode < 0 ? 0 : -1;\n        else if (typeof to == \"boolean\")\n            this.inputState.tabFocusMode = to ? 0 : -1;\n        else if (this.inputState.tabFocusMode != 0)\n            this.inputState.tabFocusMode = Date.now() + to;\n    }\n    /**\n    Returns an extension that can be used to add DOM event handlers.\n    The value should be an object mapping event names to handler\n    functions. For any given event, such functions are ordered by\n    extension precedence, and the first handler to return true will\n    be assumed to have handled that event, and no other handlers or\n    built-in behavior will be activated for it. These are registered\n    on the [content element](https://codemirror.net/6/docs/ref/#view.EditorView.contentDOM), except\n    for `scroll` handlers, which will be called any time the\n    editor's [scroll element](https://codemirror.net/6/docs/ref/#view.EditorView.scrollDOM) or one of\n    its parent nodes is scrolled.\n    */\n    static domEventHandlers(handlers) {\n        return ViewPlugin.define(() => ({}), { eventHandlers: handlers });\n    }\n    /**\n    Create an extension that registers DOM event observers. Contrary\n    to event [handlers](https://codemirror.net/6/docs/ref/#view.EditorView^domEventHandlers),\n    observers can't be prevented from running by a higher-precedence\n    handler returning true. They also don't prevent other handlers\n    and observers from running when they return true, and should not\n    call `preventDefault`.\n    */\n    static domEventObservers(observers) {\n        return ViewPlugin.define(() => ({}), { eventObservers: observers });\n    }\n    /**\n    Create a theme extension. The first argument can be a\n    [`style-mod`](https://github.com/marijnh/style-mod#documentation)\n    style spec providing the styles for the theme. These will be\n    prefixed with a generated class for the style.\n    \n    Because the selectors will be prefixed with a scope class, rule\n    that directly match the editor's [wrapper\n    element](https://codemirror.net/6/docs/ref/#view.EditorView.dom)—to which the scope class will be\n    added—need to be explicitly differentiated by adding an `&` to\n    the selector for that element—for example\n    `&.cm-focused`.\n    \n    When `dark` is set to true, the theme will be marked as dark,\n    which will cause the `&dark` rules from [base\n    themes](https://codemirror.net/6/docs/ref/#view.EditorView^baseTheme) to be used (as opposed to\n    `&light` when a light theme is active).\n    */\n    static theme(spec, options) {\n        let prefix = style_mod__WEBPACK_IMPORTED_MODULE_0__.StyleModule.newName();\n        let result = [theme.of(prefix), styleModule.of(buildTheme(`.${prefix}`, spec))];\n        if (options && options.dark)\n            result.push(darkTheme.of(true));\n        return result;\n    }\n    /**\n    Create an extension that adds styles to the base theme. Like\n    with [`theme`](https://codemirror.net/6/docs/ref/#view.EditorView^theme), use `&` to indicate the\n    place of the editor wrapper element when directly targeting\n    that. You can also use `&dark` or `&light` instead to only\n    target editors with a dark or light theme.\n    */\n    static baseTheme(spec) {\n        return _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.Prec.lowest(styleModule.of(buildTheme(\".\" + baseThemeID, spec, lightDarkIDs)));\n    }\n    /**\n    Retrieve an editor view instance from the view's DOM\n    representation.\n    */\n    static findFromDOM(dom) {\n        var _a;\n        let content = dom.querySelector(\".cm-content\");\n        let cView = content && ContentView.get(content) || ContentView.get(dom);\n        return ((_a = cView === null || cView === void 0 ? void 0 : cView.rootView) === null || _a === void 0 ? void 0 : _a.view) || null;\n    }\n}\n/**\nFacet to add a [style\nmodule](https://github.com/marijnh/style-mod#documentation) to\nan editor view. The view will ensure that the module is\nmounted in its [document\nroot](https://codemirror.net/6/docs/ref/#view.EditorView.constructor^config.root).\n*/\nEditorView.styleModule = styleModule;\n/**\nAn input handler can override the way changes to the editable\nDOM content are handled. Handlers are passed the document\npositions between which the change was found, and the new\ncontent. When one returns true, no further input handlers are\ncalled and the default behavior is prevented.\n\nThe `insert` argument can be used to get the default transaction\nthat would be applied for this input. This can be useful when\ndispatching the custom behavior as a separate transaction.\n*/\nEditorView.inputHandler = inputHandler;\n/**\nScroll handlers can override how things are scrolled into view.\nIf they return `true`, no further handling happens for the\nscrolling. If they return false, the default scroll behavior is\napplied. Scroll handlers should never initiate editor updates.\n*/\nEditorView.scrollHandler = scrollHandler;\n/**\nThis facet can be used to provide functions that create effects\nto be dispatched when the editor's focus state changes.\n*/\nEditorView.focusChangeEffect = focusChangeEffect;\n/**\nBy default, the editor assumes all its content has the same\n[text direction](https://codemirror.net/6/docs/ref/#view.Direction). Configure this with a `true`\nvalue to make it read the text direction of every (rendered)\nline separately.\n*/\nEditorView.perLineTextDirection = perLineTextDirection;\n/**\nAllows you to provide a function that should be called when the\nlibrary catches an exception from an extension (mostly from view\nplugins, but may be used by other extensions to route exceptions\nfrom user-code-provided callbacks). This is mostly useful for\ndebugging and logging. See [`logException`](https://codemirror.net/6/docs/ref/#view.logException).\n*/\nEditorView.exceptionSink = exceptionSink;\n/**\nA facet that can be used to register a function to be called\nevery time the view updates.\n*/\nEditorView.updateListener = updateListener;\n/**\nFacet that controls whether the editor content DOM is editable.\nWhen its highest-precedence value is `false`, the element will\nnot have its `contenteditable` attribute set. (Note that this\ndoesn't affect API calls that change the editor content, even\nwhen those are bound to keys or buttons. See the\n[`readOnly`](https://codemirror.net/6/docs/ref/#state.EditorState.readOnly) facet for that.)\n*/\nEditorView.editable = editable;\n/**\nAllows you to influence the way mouse selection happens. The\nfunctions in this facet will be called for a `mousedown` event\non the editor, and can return an object that overrides the way a\nselection is computed from that mouse click or drag.\n*/\nEditorView.mouseSelectionStyle = mouseSelectionStyle;\n/**\nFacet used to configure whether a given selection drag event\nshould move or copy the selection. The given predicate will be\ncalled with the `mousedown` event, and can return `true` when\nthe drag should move the content.\n*/\nEditorView.dragMovesSelection = dragMovesSelection$1;\n/**\nFacet used to configure whether a given selecting click adds a\nnew range to the existing selection or replaces it entirely. The\ndefault behavior is to check `event.metaKey` on macOS, and\n`event.ctrlKey` elsewhere.\n*/\nEditorView.clickAddsSelectionRange = clickAddsSelectionRange;\n/**\nA facet that determines which [decorations](https://codemirror.net/6/docs/ref/#view.Decoration)\nare shown in the view. Decorations can be provided in two\nways—directly, or via a function that takes an editor view.\n\nOnly decoration sets provided directly are allowed to influence\nthe editor's vertical layout structure. The ones provided as\nfunctions are called _after_ the new viewport has been computed,\nand thus **must not** introduce block widgets or replacing\ndecorations that cover line breaks.\n\nIf you want decorated ranges to behave like atomic units for\ncursor motion and deletion purposes, also provide the range set\ncontaining the decorations to\n[`EditorView.atomicRanges`](https://codemirror.net/6/docs/ref/#view.EditorView^atomicRanges).\n*/\nEditorView.decorations = decorations;\n/**\nFacet that works much like\n[`decorations`](https://codemirror.net/6/docs/ref/#view.EditorView^decorations), but puts its\ninputs at the very bottom of the precedence stack, meaning mark\ndecorations provided here will only be split by other, partially\noverlapping \\`outerDecorations\\` ranges, and wrap around all\nregular decorations. Use this for mark elements that should, as\nmuch as possible, remain in one piece.\n*/\nEditorView.outerDecorations = outerDecorations;\n/**\nUsed to provide ranges that should be treated as atoms as far as\ncursor motion is concerned. This causes methods like\n[`moveByChar`](https://codemirror.net/6/docs/ref/#view.EditorView.moveByChar) and\n[`moveVertically`](https://codemirror.net/6/docs/ref/#view.EditorView.moveVertically) (and the\ncommands built on top of them) to skip across such regions when\na selection endpoint would enter them. This does _not_ prevent\ndirect programmatic [selection\nupdates](https://codemirror.net/6/docs/ref/#state.TransactionSpec.selection) from moving into such\nregions.\n*/\nEditorView.atomicRanges = atomicRanges;\n/**\nWhen range decorations add a `unicode-bidi: isolate` style, they\nshould also include a\n[`bidiIsolate`](https://codemirror.net/6/docs/ref/#view.MarkDecorationSpec.bidiIsolate) property\nin their decoration spec, and be exposed through this facet, so\nthat the editor can compute the proper text order. (Other values\nfor `unicode-bidi`, except of course `normal`, are not\nsupported.)\n*/\nEditorView.bidiIsolatedRanges = bidiIsolatedRanges;\n/**\nFacet that allows extensions to provide additional scroll\nmargins (space around the sides of the scrolling element that\nshould be considered invisible). This can be useful when the\nplugin introduces elements that cover part of that element (for\nexample a horizontally fixed gutter).\n*/\nEditorView.scrollMargins = scrollMargins;\n/**\nThis facet records whether a dark theme is active. The extension\nreturned by [`theme`](https://codemirror.net/6/docs/ref/#view.EditorView^theme) automatically\nincludes an instance of this when the `dark` option is set to\ntrue.\n*/\nEditorView.darkTheme = darkTheme;\n/**\nProvides a Content Security Policy nonce to use when creating\nthe style sheets for the editor. Holds the empty string when no\nnonce has been provided.\n*/\nEditorView.cspNonce = /*@__PURE__*/_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.Facet.define({ combine: values => values.length ? values[0] : \"\" });\n/**\nFacet that provides additional DOM attributes for the editor's\neditable DOM element.\n*/\nEditorView.contentAttributes = contentAttributes;\n/**\nFacet that provides DOM attributes for the editor's outer\nelement.\n*/\nEditorView.editorAttributes = editorAttributes;\n/**\nAn extension that enables line wrapping in the editor (by\nsetting CSS `white-space` to `pre-wrap` in the content).\n*/\nEditorView.lineWrapping = /*@__PURE__*/EditorView.contentAttributes.of({ \"class\": \"cm-lineWrapping\" });\n/**\nState effect used to include screen reader announcements in a\ntransaction. These will be added to the DOM in a visually hidden\nelement with `aria-live=\"polite\"` set, and should be used to\ndescribe effects that are visually obvious but may not be\nnoticed by screen reader users (such as moving to the next\nsearch match).\n*/\nEditorView.announce = /*@__PURE__*/_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.StateEffect.define();\n// Maximum line length for which we compute accurate bidi info\nconst MaxBidiLine = 4096;\nconst BadMeasure = {};\nclass CachedOrder {\n    constructor(from, to, dir, isolates, fresh, order) {\n        this.from = from;\n        this.to = to;\n        this.dir = dir;\n        this.isolates = isolates;\n        this.fresh = fresh;\n        this.order = order;\n    }\n    static update(cache, changes) {\n        if (changes.empty && !cache.some(c => c.fresh))\n            return cache;\n        let result = [], lastDir = cache.length ? cache[cache.length - 1].dir : Direction.LTR;\n        for (let i = Math.max(0, cache.length - 10); i < cache.length; i++) {\n            let entry = cache[i];\n            if (entry.dir == lastDir && !changes.touchesRange(entry.from, entry.to))\n                result.push(new CachedOrder(changes.mapPos(entry.from, 1), changes.mapPos(entry.to, -1), entry.dir, entry.isolates, false, entry.order));\n        }\n        return result;\n    }\n}\nfunction attrsFromFacet(view, facet, base) {\n    for (let sources = view.state.facet(facet), i = sources.length - 1; i >= 0; i--) {\n        let source = sources[i], value = typeof source == \"function\" ? source(view) : source;\n        if (value)\n            combineAttrs(value, base);\n    }\n    return base;\n}\n\nconst currentPlatform = browser.mac ? \"mac\" : browser.windows ? \"win\" : browser.linux ? \"linux\" : \"key\";\nfunction normalizeKeyName(name, platform) {\n    const parts = name.split(/-(?!$)/);\n    let result = parts[parts.length - 1];\n    if (result == \"Space\")\n        result = \" \";\n    let alt, ctrl, shift, meta;\n    for (let i = 0; i < parts.length - 1; ++i) {\n        const mod = parts[i];\n        if (/^(cmd|meta|m)$/i.test(mod))\n            meta = true;\n        else if (/^a(lt)?$/i.test(mod))\n            alt = true;\n        else if (/^(c|ctrl|control)$/i.test(mod))\n            ctrl = true;\n        else if (/^s(hift)?$/i.test(mod))\n            shift = true;\n        else if (/^mod$/i.test(mod)) {\n            if (platform == \"mac\")\n                meta = true;\n            else\n                ctrl = true;\n        }\n        else\n            throw new Error(\"Unrecognized modifier name: \" + mod);\n    }\n    if (alt)\n        result = \"Alt-\" + result;\n    if (ctrl)\n        result = \"Ctrl-\" + result;\n    if (meta)\n        result = \"Meta-\" + result;\n    if (shift)\n        result = \"Shift-\" + result;\n    return result;\n}\nfunction modifiers(name, event, shift) {\n    if (event.altKey)\n        name = \"Alt-\" + name;\n    if (event.ctrlKey)\n        name = \"Ctrl-\" + name;\n    if (event.metaKey)\n        name = \"Meta-\" + name;\n    if (shift !== false && event.shiftKey)\n        name = \"Shift-\" + name;\n    return name;\n}\nconst handleKeyEvents = /*@__PURE__*/_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.Prec.default(/*@__PURE__*/EditorView.domEventHandlers({\n    keydown(event, view) {\n        return runHandlers(getKeymap(view.state), event, view, \"editor\");\n    }\n}));\n/**\nFacet used for registering keymaps.\n\nYou can add multiple keymaps to an editor. Their priorities\ndetermine their precedence (the ones specified early or with high\npriority get checked first). When a handler has returned `true`\nfor a given key, no further handlers are called.\n*/\nconst keymap = /*@__PURE__*/_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.Facet.define({ enables: handleKeyEvents });\nconst Keymaps = /*@__PURE__*/new WeakMap();\n// This is hidden behind an indirection, rather than directly computed\n// by the facet, to keep internal types out of the facet's type.\nfunction getKeymap(state) {\n    let bindings = state.facet(keymap);\n    let map = Keymaps.get(bindings);\n    if (!map)\n        Keymaps.set(bindings, map = buildKeymap(bindings.reduce((a, b) => a.concat(b), [])));\n    return map;\n}\n/**\nRun the key handlers registered for a given scope. The event\nobject should be a `\"keydown\"` event. Returns true if any of the\nhandlers handled it.\n*/\nfunction runScopeHandlers(view, event, scope) {\n    return runHandlers(getKeymap(view.state), event, view, scope);\n}\nlet storedPrefix = null;\nconst PrefixTimeout = 4000;\nfunction buildKeymap(bindings, platform = currentPlatform) {\n    let bound = Object.create(null);\n    let isPrefix = Object.create(null);\n    let checkPrefix = (name, is) => {\n        let current = isPrefix[name];\n        if (current == null)\n            isPrefix[name] = is;\n        else if (current != is)\n            throw new Error(\"Key binding \" + name + \" is used both as a regular binding and as a multi-stroke prefix\");\n    };\n    let add = (scope, key, command, preventDefault, stopPropagation) => {\n        var _a, _b;\n        let scopeObj = bound[scope] || (bound[scope] = Object.create(null));\n        let parts = key.split(/ (?!$)/).map(k => normalizeKeyName(k, platform));\n        for (let i = 1; i < parts.length; i++) {\n            let prefix = parts.slice(0, i).join(\" \");\n            checkPrefix(prefix, true);\n            if (!scopeObj[prefix])\n                scopeObj[prefix] = {\n                    preventDefault: true,\n                    stopPropagation: false,\n                    run: [(view) => {\n                            let ourObj = storedPrefix = { view, prefix, scope };\n                            setTimeout(() => { if (storedPrefix == ourObj)\n                                storedPrefix = null; }, PrefixTimeout);\n                            return true;\n                        }]\n                };\n        }\n        let full = parts.join(\" \");\n        checkPrefix(full, false);\n        let binding = scopeObj[full] || (scopeObj[full] = {\n            preventDefault: false,\n            stopPropagation: false,\n            run: ((_b = (_a = scopeObj._any) === null || _a === void 0 ? void 0 : _a.run) === null || _b === void 0 ? void 0 : _b.slice()) || []\n        });\n        if (command)\n            binding.run.push(command);\n        if (preventDefault)\n            binding.preventDefault = true;\n        if (stopPropagation)\n            binding.stopPropagation = true;\n    };\n    for (let b of bindings) {\n        let scopes = b.scope ? b.scope.split(\" \") : [\"editor\"];\n        if (b.any)\n            for (let scope of scopes) {\n                let scopeObj = bound[scope] || (bound[scope] = Object.create(null));\n                if (!scopeObj._any)\n                    scopeObj._any = { preventDefault: false, stopPropagation: false, run: [] };\n                let { any } = b;\n                for (let key in scopeObj)\n                    scopeObj[key].run.push(view => any(view, currentKeyEvent));\n            }\n        let name = b[platform] || b.key;\n        if (!name)\n            continue;\n        for (let scope of scopes) {\n            add(scope, name, b.run, b.preventDefault, b.stopPropagation);\n            if (b.shift)\n                add(scope, \"Shift-\" + name, b.shift, b.preventDefault, b.stopPropagation);\n        }\n    }\n    return bound;\n}\nlet currentKeyEvent = null;\nfunction runHandlers(map, event, view, scope) {\n    currentKeyEvent = event;\n    let name = (0,w3c_keyname__WEBPACK_IMPORTED_MODULE_1__.keyName)(event);\n    let charCode = (0,_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.codePointAt)(name, 0), isChar = (0,_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.codePointSize)(charCode) == name.length && name != \" \";\n    let prefix = \"\", handled = false, prevented = false, stopPropagation = false;\n    if (storedPrefix && storedPrefix.view == view && storedPrefix.scope == scope) {\n        prefix = storedPrefix.prefix + \" \";\n        if (modifierCodes.indexOf(event.keyCode) < 0) {\n            prevented = true;\n            storedPrefix = null;\n        }\n    }\n    let ran = new Set;\n    let runFor = (binding) => {\n        if (binding) {\n            for (let cmd of binding.run)\n                if (!ran.has(cmd)) {\n                    ran.add(cmd);\n                    if (cmd(view)) {\n                        if (binding.stopPropagation)\n                            stopPropagation = true;\n                        return true;\n                    }\n                }\n            if (binding.preventDefault) {\n                if (binding.stopPropagation)\n                    stopPropagation = true;\n                prevented = true;\n            }\n        }\n        return false;\n    };\n    let scopeObj = map[scope], baseName, shiftName;\n    if (scopeObj) {\n        if (runFor(scopeObj[prefix + modifiers(name, event, !isChar)])) {\n            handled = true;\n        }\n        else if (isChar && (event.altKey || event.metaKey || event.ctrlKey) &&\n            // Ctrl-Alt may be used for AltGr on Windows\n            !(browser.windows && event.ctrlKey && event.altKey) &&\n            (baseName = w3c_keyname__WEBPACK_IMPORTED_MODULE_1__.base[event.keyCode]) && baseName != name) {\n            if (runFor(scopeObj[prefix + modifiers(baseName, event, true)])) {\n                handled = true;\n            }\n            else if (event.shiftKey && (shiftName = w3c_keyname__WEBPACK_IMPORTED_MODULE_1__.shift[event.keyCode]) != name && shiftName != baseName &&\n                runFor(scopeObj[prefix + modifiers(shiftName, event, false)])) {\n                handled = true;\n            }\n        }\n        else if (isChar && event.shiftKey &&\n            runFor(scopeObj[prefix + modifiers(name, event, true)])) {\n            handled = true;\n        }\n        if (!handled && runFor(scopeObj._any))\n            handled = true;\n    }\n    if (prevented)\n        handled = true;\n    if (handled && stopPropagation)\n        event.stopPropagation();\n    currentKeyEvent = null;\n    return handled;\n}\n\n/**\nImplementation of [`LayerMarker`](https://codemirror.net/6/docs/ref/#view.LayerMarker) that creates\na rectangle at a given set of coordinates.\n*/\nclass RectangleMarker {\n    /**\n    Create a marker with the given class and dimensions. If `width`\n    is null, the DOM element will get no width style.\n    */\n    constructor(className, \n    /**\n    The left position of the marker (in pixels, document-relative).\n    */\n    left, \n    /**\n    The top position of the marker.\n    */\n    top, \n    /**\n    The width of the marker, or null if it shouldn't get a width assigned.\n    */\n    width, \n    /**\n    The height of the marker.\n    */\n    height) {\n        this.className = className;\n        this.left = left;\n        this.top = top;\n        this.width = width;\n        this.height = height;\n    }\n    draw() {\n        let elt = document.createElement(\"div\");\n        elt.className = this.className;\n        this.adjust(elt);\n        return elt;\n    }\n    update(elt, prev) {\n        if (prev.className != this.className)\n            return false;\n        this.adjust(elt);\n        return true;\n    }\n    adjust(elt) {\n        elt.style.left = this.left + \"px\";\n        elt.style.top = this.top + \"px\";\n        if (this.width != null)\n            elt.style.width = this.width + \"px\";\n        elt.style.height = this.height + \"px\";\n    }\n    eq(p) {\n        return this.left == p.left && this.top == p.top && this.width == p.width && this.height == p.height &&\n            this.className == p.className;\n    }\n    /**\n    Create a set of rectangles for the given selection range,\n    assigning them theclass`className`. Will create a single\n    rectangle for empty ranges, and a set of selection-style\n    rectangles covering the range's content (in a bidi-aware\n    way) for non-empty ones.\n    */\n    static forRange(view, className, range) {\n        if (range.empty) {\n            let pos = view.coordsAtPos(range.head, range.assoc || 1);\n            if (!pos)\n                return [];\n            let base = getBase(view);\n            return [new RectangleMarker(className, pos.left - base.left, pos.top - base.top, null, pos.bottom - pos.top)];\n        }\n        else {\n            return rectanglesForRange(view, className, range);\n        }\n    }\n}\nfunction getBase(view) {\n    let rect = view.scrollDOM.getBoundingClientRect();\n    let left = view.textDirection == Direction.LTR ? rect.left : rect.right - view.scrollDOM.clientWidth * view.scaleX;\n    return { left: left - view.scrollDOM.scrollLeft * view.scaleX, top: rect.top - view.scrollDOM.scrollTop * view.scaleY };\n}\nfunction wrappedLine(view, pos, side, inside) {\n    let coords = view.coordsAtPos(pos, side * 2);\n    if (!coords)\n        return inside;\n    let editorRect = view.dom.getBoundingClientRect();\n    let y = (coords.top + coords.bottom) / 2;\n    let left = view.posAtCoords({ x: editorRect.left + 1, y });\n    let right = view.posAtCoords({ x: editorRect.right - 1, y });\n    if (left == null || right == null)\n        return inside;\n    return { from: Math.max(inside.from, Math.min(left, right)), to: Math.min(inside.to, Math.max(left, right)) };\n}\nfunction rectanglesForRange(view, className, range) {\n    if (range.to <= view.viewport.from || range.from >= view.viewport.to)\n        return [];\n    let from = Math.max(range.from, view.viewport.from), to = Math.min(range.to, view.viewport.to);\n    let ltr = view.textDirection == Direction.LTR;\n    let content = view.contentDOM, contentRect = content.getBoundingClientRect(), base = getBase(view);\n    let lineElt = content.querySelector(\".cm-line\"), lineStyle = lineElt && window.getComputedStyle(lineElt);\n    let leftSide = contentRect.left +\n        (lineStyle ? parseInt(lineStyle.paddingLeft) + Math.min(0, parseInt(lineStyle.textIndent)) : 0);\n    let rightSide = contentRect.right - (lineStyle ? parseInt(lineStyle.paddingRight) : 0);\n    let startBlock = blockAt(view, from), endBlock = blockAt(view, to);\n    let visualStart = startBlock.type == BlockType.Text ? startBlock : null;\n    let visualEnd = endBlock.type == BlockType.Text ? endBlock : null;\n    if (visualStart && (view.lineWrapping || startBlock.widgetLineBreaks))\n        visualStart = wrappedLine(view, from, 1, visualStart);\n    if (visualEnd && (view.lineWrapping || endBlock.widgetLineBreaks))\n        visualEnd = wrappedLine(view, to, -1, visualEnd);\n    if (visualStart && visualEnd && visualStart.from == visualEnd.from && visualStart.to == visualEnd.to) {\n        return pieces(drawForLine(range.from, range.to, visualStart));\n    }\n    else {\n        let top = visualStart ? drawForLine(range.from, null, visualStart) : drawForWidget(startBlock, false);\n        let bottom = visualEnd ? drawForLine(null, range.to, visualEnd) : drawForWidget(endBlock, true);\n        let between = [];\n        if ((visualStart || startBlock).to < (visualEnd || endBlock).from - (visualStart && visualEnd ? 1 : 0) ||\n            startBlock.widgetLineBreaks > 1 && top.bottom + view.defaultLineHeight / 2 < bottom.top)\n            between.push(piece(leftSide, top.bottom, rightSide, bottom.top));\n        else if (top.bottom < bottom.top && view.elementAtHeight((top.bottom + bottom.top) / 2).type == BlockType.Text)\n            top.bottom = bottom.top = (top.bottom + bottom.top) / 2;\n        return pieces(top).concat(between).concat(pieces(bottom));\n    }\n    function piece(left, top, right, bottom) {\n        return new RectangleMarker(className, left - base.left, top - base.top - 0.01 /* C.Epsilon */, right - left, bottom - top + 0.01 /* C.Epsilon */);\n    }\n    function pieces({ top, bottom, horizontal }) {\n        let pieces = [];\n        for (let i = 0; i < horizontal.length; i += 2)\n            pieces.push(piece(horizontal[i], top, horizontal[i + 1], bottom));\n        return pieces;\n    }\n    // Gets passed from/to in line-local positions\n    function drawForLine(from, to, line) {\n        let top = 1e9, bottom = -1e9, horizontal = [];\n        function addSpan(from, fromOpen, to, toOpen, dir) {\n            // Passing 2/-2 is a kludge to force the view to return\n            // coordinates on the proper side of block widgets, since\n            // normalizing the side there, though appropriate for most\n            // coordsAtPos queries, would break selection drawing.\n            let fromCoords = view.coordsAtPos(from, (from == line.to ? -2 : 2));\n            let toCoords = view.coordsAtPos(to, (to == line.from ? 2 : -2));\n            if (!fromCoords || !toCoords)\n                return;\n            top = Math.min(fromCoords.top, toCoords.top, top);\n            bottom = Math.max(fromCoords.bottom, toCoords.bottom, bottom);\n            if (dir == Direction.LTR)\n                horizontal.push(ltr && fromOpen ? leftSide : fromCoords.left, ltr && toOpen ? rightSide : toCoords.right);\n            else\n                horizontal.push(!ltr && toOpen ? leftSide : toCoords.left, !ltr && fromOpen ? rightSide : fromCoords.right);\n        }\n        let start = from !== null && from !== void 0 ? from : line.from, end = to !== null && to !== void 0 ? to : line.to;\n        // Split the range by visible range and document line\n        for (let r of view.visibleRanges)\n            if (r.to > start && r.from < end) {\n                for (let pos = Math.max(r.from, start), endPos = Math.min(r.to, end);;) {\n                    let docLine = view.state.doc.lineAt(pos);\n                    for (let span of view.bidiSpans(docLine)) {\n                        let spanFrom = span.from + docLine.from, spanTo = span.to + docLine.from;\n                        if (spanFrom >= endPos)\n                            break;\n                        if (spanTo > pos)\n                            addSpan(Math.max(spanFrom, pos), from == null && spanFrom <= start, Math.min(spanTo, endPos), to == null && spanTo >= end, span.dir);\n                    }\n                    pos = docLine.to + 1;\n                    if (pos >= endPos)\n                        break;\n                }\n            }\n        if (horizontal.length == 0)\n            addSpan(start, from == null, end, to == null, view.textDirection);\n        return { top, bottom, horizontal };\n    }\n    function drawForWidget(block, top) {\n        let y = contentRect.top + (top ? block.top : block.bottom);\n        return { top: y, bottom: y, horizontal: [] };\n    }\n}\nfunction sameMarker(a, b) {\n    return a.constructor == b.constructor && a.eq(b);\n}\nclass LayerView {\n    constructor(view, layer) {\n        this.view = view;\n        this.layer = layer;\n        this.drawn = [];\n        this.scaleX = 1;\n        this.scaleY = 1;\n        this.measureReq = { read: this.measure.bind(this), write: this.draw.bind(this) };\n        this.dom = view.scrollDOM.appendChild(document.createElement(\"div\"));\n        this.dom.classList.add(\"cm-layer\");\n        if (layer.above)\n            this.dom.classList.add(\"cm-layer-above\");\n        if (layer.class)\n            this.dom.classList.add(layer.class);\n        this.scale();\n        this.dom.setAttribute(\"aria-hidden\", \"true\");\n        this.setOrder(view.state);\n        view.requestMeasure(this.measureReq);\n        if (layer.mount)\n            layer.mount(this.dom, view);\n    }\n    update(update) {\n        if (update.startState.facet(layerOrder) != update.state.facet(layerOrder))\n            this.setOrder(update.state);\n        if (this.layer.update(update, this.dom) || update.geometryChanged) {\n            this.scale();\n            update.view.requestMeasure(this.measureReq);\n        }\n    }\n    docViewUpdate(view) {\n        if (this.layer.updateOnDocViewUpdate !== false)\n            view.requestMeasure(this.measureReq);\n    }\n    setOrder(state) {\n        let pos = 0, order = state.facet(layerOrder);\n        while (pos < order.length && order[pos] != this.layer)\n            pos++;\n        this.dom.style.zIndex = String((this.layer.above ? 150 : -1) - pos);\n    }\n    measure() {\n        return this.layer.markers(this.view);\n    }\n    scale() {\n        let { scaleX, scaleY } = this.view;\n        if (scaleX != this.scaleX || scaleY != this.scaleY) {\n            this.scaleX = scaleX;\n            this.scaleY = scaleY;\n            this.dom.style.transform = `scale(${1 / scaleX}, ${1 / scaleY})`;\n        }\n    }\n    draw(markers) {\n        if (markers.length != this.drawn.length || markers.some((p, i) => !sameMarker(p, this.drawn[i]))) {\n            let old = this.dom.firstChild, oldI = 0;\n            for (let marker of markers) {\n                if (marker.update && old && marker.constructor && this.drawn[oldI].constructor &&\n                    marker.update(old, this.drawn[oldI])) {\n                    old = old.nextSibling;\n                    oldI++;\n                }\n                else {\n                    this.dom.insertBefore(marker.draw(), old);\n                }\n            }\n            while (old) {\n                let next = old.nextSibling;\n                old.remove();\n                old = next;\n            }\n            this.drawn = markers;\n        }\n    }\n    destroy() {\n        if (this.layer.destroy)\n            this.layer.destroy(this.dom, this.view);\n        this.dom.remove();\n    }\n}\nconst layerOrder = /*@__PURE__*/_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.Facet.define();\n/**\nDefine a layer.\n*/\nfunction layer(config) {\n    return [\n        ViewPlugin.define(v => new LayerView(v, config)),\n        layerOrder.of(config)\n    ];\n}\n\nconst CanHidePrimary = !browser.ios; // FIXME test IE\nconst selectionConfig = /*@__PURE__*/_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.Facet.define({\n    combine(configs) {\n        return (0,_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.combineConfig)(configs, {\n            cursorBlinkRate: 1200,\n            drawRangeCursor: true\n        }, {\n            cursorBlinkRate: (a, b) => Math.min(a, b),\n            drawRangeCursor: (a, b) => a || b\n        });\n    }\n});\n/**\nReturns an extension that hides the browser's native selection and\ncursor, replacing the selection with a background behind the text\n(with the `cm-selectionBackground` class), and the\ncursors with elements overlaid over the code (using\n`cm-cursor-primary` and `cm-cursor-secondary`).\n\nThis allows the editor to display secondary selection ranges, and\ntends to produce a type of selection more in line with that users\nexpect in a text editor (the native selection styling will often\nleave gaps between lines and won't fill the horizontal space after\na line when the selection continues past it).\n\nIt does have a performance cost, in that it requires an extra DOM\nlayout cycle for many updates (the selection is drawn based on DOM\nlayout information that's only available after laying out the\ncontent).\n*/\nfunction drawSelection(config = {}) {\n    return [\n        selectionConfig.of(config),\n        cursorLayer,\n        selectionLayer,\n        hideNativeSelection,\n        nativeSelectionHidden.of(true)\n    ];\n}\n/**\nRetrieve the [`drawSelection`](https://codemirror.net/6/docs/ref/#view.drawSelection) configuration\nfor this state. (Note that this will return a set of defaults even\nif `drawSelection` isn't enabled.)\n*/\nfunction getDrawSelectionConfig(state) {\n    return state.facet(selectionConfig);\n}\nfunction configChanged(update) {\n    return update.startState.facet(selectionConfig) != update.state.facet(selectionConfig);\n}\nconst cursorLayer = /*@__PURE__*/layer({\n    above: true,\n    markers(view) {\n        let { state } = view, conf = state.facet(selectionConfig);\n        let cursors = [];\n        for (let r of state.selection.ranges) {\n            let prim = r == state.selection.main;\n            if (r.empty ? !prim || CanHidePrimary : conf.drawRangeCursor) {\n                let className = prim ? \"cm-cursor cm-cursor-primary\" : \"cm-cursor cm-cursor-secondary\";\n                let cursor = r.empty ? r : _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.EditorSelection.cursor(r.head, r.head > r.anchor ? -1 : 1);\n                for (let piece of RectangleMarker.forRange(view, className, cursor))\n                    cursors.push(piece);\n            }\n        }\n        return cursors;\n    },\n    update(update, dom) {\n        if (update.transactions.some(tr => tr.selection))\n            dom.style.animationName = dom.style.animationName == \"cm-blink\" ? \"cm-blink2\" : \"cm-blink\";\n        let confChange = configChanged(update);\n        if (confChange)\n            setBlinkRate(update.state, dom);\n        return update.docChanged || update.selectionSet || confChange;\n    },\n    mount(dom, view) {\n        setBlinkRate(view.state, dom);\n    },\n    class: \"cm-cursorLayer\"\n});\nfunction setBlinkRate(state, dom) {\n    dom.style.animationDuration = state.facet(selectionConfig).cursorBlinkRate + \"ms\";\n}\nconst selectionLayer = /*@__PURE__*/layer({\n    above: false,\n    markers(view) {\n        return view.state.selection.ranges.map(r => r.empty ? [] : RectangleMarker.forRange(view, \"cm-selectionBackground\", r))\n            .reduce((a, b) => a.concat(b));\n    },\n    update(update, dom) {\n        return update.docChanged || update.selectionSet || update.viewportChanged || configChanged(update);\n    },\n    class: \"cm-selectionLayer\"\n});\nconst themeSpec = {\n    \".cm-line\": {\n        \"& ::selection, &::selection\": { backgroundColor: \"transparent !important\" },\n    },\n    \".cm-content\": {\n        \"& :focus\": {\n            caretColor: \"initial !important\",\n            \"&::selection, & ::selection\": {\n                backgroundColor: \"Highlight !important\"\n            }\n        }\n    }\n};\nif (CanHidePrimary)\n    themeSpec[\".cm-line\"].caretColor = themeSpec[\".cm-content\"].caretColor = \"transparent !important\";\nconst hideNativeSelection = /*@__PURE__*/_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.Prec.highest(/*@__PURE__*/EditorView.theme(themeSpec));\n\nconst setDropCursorPos = /*@__PURE__*/_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.StateEffect.define({\n    map(pos, mapping) { return pos == null ? null : mapping.mapPos(pos); }\n});\nconst dropCursorPos = /*@__PURE__*/_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.StateField.define({\n    create() { return null; },\n    update(pos, tr) {\n        if (pos != null)\n            pos = tr.changes.mapPos(pos);\n        return tr.effects.reduce((pos, e) => e.is(setDropCursorPos) ? e.value : pos, pos);\n    }\n});\nconst drawDropCursor = /*@__PURE__*/ViewPlugin.fromClass(class {\n    constructor(view) {\n        this.view = view;\n        this.cursor = null;\n        this.measureReq = { read: this.readPos.bind(this), write: this.drawCursor.bind(this) };\n    }\n    update(update) {\n        var _a;\n        let cursorPos = update.state.field(dropCursorPos);\n        if (cursorPos == null) {\n            if (this.cursor != null) {\n                (_a = this.cursor) === null || _a === void 0 ? void 0 : _a.remove();\n                this.cursor = null;\n            }\n        }\n        else {\n            if (!this.cursor) {\n                this.cursor = this.view.scrollDOM.appendChild(document.createElement(\"div\"));\n                this.cursor.className = \"cm-dropCursor\";\n            }\n            if (update.startState.field(dropCursorPos) != cursorPos || update.docChanged || update.geometryChanged)\n                this.view.requestMeasure(this.measureReq);\n        }\n    }\n    readPos() {\n        let { view } = this;\n        let pos = view.state.field(dropCursorPos);\n        let rect = pos != null && view.coordsAtPos(pos);\n        if (!rect)\n            return null;\n        let outer = view.scrollDOM.getBoundingClientRect();\n        return {\n            left: rect.left - outer.left + view.scrollDOM.scrollLeft * view.scaleX,\n            top: rect.top - outer.top + view.scrollDOM.scrollTop * view.scaleY,\n            height: rect.bottom - rect.top\n        };\n    }\n    drawCursor(pos) {\n        if (this.cursor) {\n            let { scaleX, scaleY } = this.view;\n            if (pos) {\n                this.cursor.style.left = pos.left / scaleX + \"px\";\n                this.cursor.style.top = pos.top / scaleY + \"px\";\n                this.cursor.style.height = pos.height / scaleY + \"px\";\n            }\n            else {\n                this.cursor.style.left = \"-100000px\";\n            }\n        }\n    }\n    destroy() {\n        if (this.cursor)\n            this.cursor.remove();\n    }\n    setDropPos(pos) {\n        if (this.view.state.field(dropCursorPos) != pos)\n            this.view.dispatch({ effects: setDropCursorPos.of(pos) });\n    }\n}, {\n    eventObservers: {\n        dragover(event) {\n            this.setDropPos(this.view.posAtCoords({ x: event.clientX, y: event.clientY }));\n        },\n        dragleave(event) {\n            if (event.target == this.view.contentDOM || !this.view.contentDOM.contains(event.relatedTarget))\n                this.setDropPos(null);\n        },\n        dragend() {\n            this.setDropPos(null);\n        },\n        drop() {\n            this.setDropPos(null);\n        }\n    }\n});\n/**\nDraws a cursor at the current drop position when something is\ndragged over the editor.\n*/\nfunction dropCursor() {\n    return [dropCursorPos, drawDropCursor];\n}\n\nfunction iterMatches(doc, re, from, to, f) {\n    re.lastIndex = 0;\n    for (let cursor = doc.iterRange(from, to), pos = from, m; !cursor.next().done; pos += cursor.value.length) {\n        if (!cursor.lineBreak)\n            while (m = re.exec(cursor.value))\n                f(pos + m.index, m);\n    }\n}\nfunction matchRanges(view, maxLength) {\n    let visible = view.visibleRanges;\n    if (visible.length == 1 && visible[0].from == view.viewport.from &&\n        visible[0].to == view.viewport.to)\n        return visible;\n    let result = [];\n    for (let { from, to } of visible) {\n        from = Math.max(view.state.doc.lineAt(from).from, from - maxLength);\n        to = Math.min(view.state.doc.lineAt(to).to, to + maxLength);\n        if (result.length && result[result.length - 1].to >= from)\n            result[result.length - 1].to = to;\n        else\n            result.push({ from, to });\n    }\n    return result;\n}\n/**\nHelper class used to make it easier to maintain decorations on\nvisible code that matches a given regular expression. To be used\nin a [view plugin](https://codemirror.net/6/docs/ref/#view.ViewPlugin). Instances of this object\nrepresent a matching configuration.\n*/\nclass MatchDecorator {\n    /**\n    Create a decorator.\n    */\n    constructor(config) {\n        const { regexp, decoration, decorate, boundary, maxLength = 1000 } = config;\n        if (!regexp.global)\n            throw new RangeError(\"The regular expression given to MatchDecorator should have its 'g' flag set\");\n        this.regexp = regexp;\n        if (decorate) {\n            this.addMatch = (match, view, from, add) => decorate(add, from, from + match[0].length, match, view);\n        }\n        else if (typeof decoration == \"function\") {\n            this.addMatch = (match, view, from, add) => {\n                let deco = decoration(match, view, from);\n                if (deco)\n                    add(from, from + match[0].length, deco);\n            };\n        }\n        else if (decoration) {\n            this.addMatch = (match, _view, from, add) => add(from, from + match[0].length, decoration);\n        }\n        else {\n            throw new RangeError(\"Either 'decorate' or 'decoration' should be provided to MatchDecorator\");\n        }\n        this.boundary = boundary;\n        this.maxLength = maxLength;\n    }\n    /**\n    Compute the full set of decorations for matches in the given\n    view's viewport. You'll want to call this when initializing your\n    plugin.\n    */\n    createDeco(view) {\n        let build = new _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.RangeSetBuilder(), add = build.add.bind(build);\n        for (let { from, to } of matchRanges(view, this.maxLength))\n            iterMatches(view.state.doc, this.regexp, from, to, (from, m) => this.addMatch(m, view, from, add));\n        return build.finish();\n    }\n    /**\n    Update a set of decorations for a view update. `deco` _must_ be\n    the set of decorations produced by _this_ `MatchDecorator` for\n    the view state before the update.\n    */\n    updateDeco(update, deco) {\n        let changeFrom = 1e9, changeTo = -1;\n        if (update.docChanged)\n            update.changes.iterChanges((_f, _t, from, to) => {\n                if (to > update.view.viewport.from && from < update.view.viewport.to) {\n                    changeFrom = Math.min(from, changeFrom);\n                    changeTo = Math.max(to, changeTo);\n                }\n            });\n        if (update.viewportChanged || changeTo - changeFrom > 1000)\n            return this.createDeco(update.view);\n        if (changeTo > -1)\n            return this.updateRange(update.view, deco.map(update.changes), changeFrom, changeTo);\n        return deco;\n    }\n    updateRange(view, deco, updateFrom, updateTo) {\n        for (let r of view.visibleRanges) {\n            let from = Math.max(r.from, updateFrom), to = Math.min(r.to, updateTo);\n            if (to > from) {\n                let fromLine = view.state.doc.lineAt(from), toLine = fromLine.to < to ? view.state.doc.lineAt(to) : fromLine;\n                let start = Math.max(r.from, fromLine.from), end = Math.min(r.to, toLine.to);\n                if (this.boundary) {\n                    for (; from > fromLine.from; from--)\n                        if (this.boundary.test(fromLine.text[from - 1 - fromLine.from])) {\n                            start = from;\n                            break;\n                        }\n                    for (; to < toLine.to; to++)\n                        if (this.boundary.test(toLine.text[to - toLine.from])) {\n                            end = to;\n                            break;\n                        }\n                }\n                let ranges = [], m;\n                let add = (from, to, deco) => ranges.push(deco.range(from, to));\n                if (fromLine == toLine) {\n                    this.regexp.lastIndex = start - fromLine.from;\n                    while ((m = this.regexp.exec(fromLine.text)) && m.index < end - fromLine.from)\n                        this.addMatch(m, view, m.index + fromLine.from, add);\n                }\n                else {\n                    iterMatches(view.state.doc, this.regexp, start, end, (from, m) => this.addMatch(m, view, from, add));\n                }\n                deco = deco.update({ filterFrom: start, filterTo: end, filter: (from, to) => from < start || to > end, add: ranges });\n            }\n        }\n        return deco;\n    }\n}\n\nconst UnicodeRegexpSupport = /x/.unicode != null ? \"gu\" : \"g\";\nconst 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);\nconst Names = {\n    0: \"null\",\n    7: \"bell\",\n    8: \"backspace\",\n    10: \"newline\",\n    11: \"vertical tab\",\n    13: \"carriage return\",\n    27: \"escape\",\n    8203: \"zero width space\",\n    8204: \"zero width non-joiner\",\n    8205: \"zero width joiner\",\n    8206: \"left-to-right mark\",\n    8207: \"right-to-left mark\",\n    8232: \"line separator\",\n    8237: \"left-to-right override\",\n    8238: \"right-to-left override\",\n    8294: \"left-to-right isolate\",\n    8295: \"right-to-left isolate\",\n    8297: \"pop directional isolate\",\n    8233: \"paragraph separator\",\n    65279: \"zero width no-break space\",\n    65532: \"object replacement\"\n};\nlet _supportsTabSize = null;\nfunction supportsTabSize() {\n    var _a;\n    if (_supportsTabSize == null && typeof document != \"undefined\" && document.body) {\n        let styles = document.body.style;\n        _supportsTabSize = ((_a = styles.tabSize) !== null && _a !== void 0 ? _a : styles.MozTabSize) != null;\n    }\n    return _supportsTabSize || false;\n}\nconst specialCharConfig = /*@__PURE__*/_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.Facet.define({\n    combine(configs) {\n        let config = (0,_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.combineConfig)(configs, {\n            render: null,\n            specialChars: Specials,\n            addSpecialChars: null\n        });\n        if (config.replaceTabs = !supportsTabSize())\n            config.specialChars = new RegExp(\"\\t|\" + config.specialChars.source, UnicodeRegexpSupport);\n        if (config.addSpecialChars)\n            config.specialChars = new RegExp(config.specialChars.source + \"|\" + config.addSpecialChars.source, UnicodeRegexpSupport);\n        return config;\n    }\n});\n/**\nReturns an extension that installs highlighting of special\ncharacters.\n*/\nfunction highlightSpecialChars(\n/**\nConfiguration options.\n*/\nconfig = {}) {\n    return [specialCharConfig.of(config), specialCharPlugin()];\n}\nlet _plugin = null;\nfunction specialCharPlugin() {\n    return _plugin || (_plugin = ViewPlugin.fromClass(class {\n        constructor(view) {\n            this.view = view;\n            this.decorations = Decoration.none;\n            this.decorationCache = Object.create(null);\n            this.decorator = this.makeDecorator(view.state.facet(specialCharConfig));\n            this.decorations = this.decorator.createDeco(view);\n        }\n        makeDecorator(conf) {\n            return new MatchDecorator({\n                regexp: conf.specialChars,\n                decoration: (m, view, pos) => {\n                    let { doc } = view.state;\n                    let code = (0,_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.codePointAt)(m[0], 0);\n                    if (code == 9) {\n                        let line = doc.lineAt(pos);\n                        let size = view.state.tabSize, col = (0,_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.countColumn)(line.text, size, pos - line.from);\n                        return Decoration.replace({\n                            widget: new TabWidget((size - (col % size)) * this.view.defaultCharacterWidth / this.view.scaleX)\n                        });\n                    }\n                    return this.decorationCache[code] ||\n                        (this.decorationCache[code] = Decoration.replace({ widget: new SpecialCharWidget(conf, code) }));\n                },\n                boundary: conf.replaceTabs ? undefined : /[^]/\n            });\n        }\n        update(update) {\n            let conf = update.state.facet(specialCharConfig);\n            if (update.startState.facet(specialCharConfig) != conf) {\n                this.decorator = this.makeDecorator(conf);\n                this.decorations = this.decorator.createDeco(update.view);\n            }\n            else {\n                this.decorations = this.decorator.updateDeco(update, this.decorations);\n            }\n        }\n    }, {\n        decorations: v => v.decorations\n    }));\n}\nconst DefaultPlaceholder = \"\\u2022\";\n// Assigns placeholder characters from the Control Pictures block to\n// ASCII control characters\nfunction placeholder$1(code) {\n    if (code >= 32)\n        return DefaultPlaceholder;\n    if (code == 10)\n        return \"\\u2424\";\n    return String.fromCharCode(9216 + code);\n}\nclass SpecialCharWidget extends WidgetType {\n    constructor(options, code) {\n        super();\n        this.options = options;\n        this.code = code;\n    }\n    eq(other) { return other.code == this.code; }\n    toDOM(view) {\n        let ph = placeholder$1(this.code);\n        let desc = view.state.phrase(\"Control character\") + \" \" + (Names[this.code] || \"0x\" + this.code.toString(16));\n        let custom = this.options.render && this.options.render(this.code, desc, ph);\n        if (custom)\n            return custom;\n        let span = document.createElement(\"span\");\n        span.textContent = ph;\n        span.title = desc;\n        span.setAttribute(\"aria-label\", desc);\n        span.className = \"cm-specialChar\";\n        return span;\n    }\n    ignoreEvent() { return false; }\n}\nclass TabWidget extends WidgetType {\n    constructor(width) {\n        super();\n        this.width = width;\n    }\n    eq(other) { return other.width == this.width; }\n    toDOM() {\n        let span = document.createElement(\"span\");\n        span.textContent = \"\\t\";\n        span.className = \"cm-tab\";\n        span.style.width = this.width + \"px\";\n        return span;\n    }\n    ignoreEvent() { return false; }\n}\n\nconst plugin = /*@__PURE__*/ViewPlugin.fromClass(class {\n    constructor() {\n        this.height = 1000;\n        this.attrs = { style: \"padding-bottom: 1000px\" };\n    }\n    update(update) {\n        let { view } = update;\n        let height = view.viewState.editorHeight -\n            view.defaultLineHeight - view.documentPadding.top - 0.5;\n        if (height >= 0 && height != this.height) {\n            this.height = height;\n            this.attrs = { style: `padding-bottom: ${height}px` };\n        }\n    }\n});\n/**\nReturns an extension that makes sure the content has a bottom\nmargin equivalent to the height of the editor, minus one line\nheight, so that every line in the document can be scrolled to the\ntop of the editor.\n\nThis is only meaningful when the editor is scrollable, and should\nnot be enabled in editors that take the size of their content.\n*/\nfunction scrollPastEnd() {\n    return [plugin, contentAttributes.of(view => { var _a; return ((_a = view.plugin(plugin)) === null || _a === void 0 ? void 0 : _a.attrs) || null; })];\n}\n\n/**\nMark lines that have a cursor on them with the `\"cm-activeLine\"`\nDOM class.\n*/\nfunction highlightActiveLine() {\n    return activeLineHighlighter;\n}\nconst lineDeco = /*@__PURE__*/Decoration.line({ class: \"cm-activeLine\" });\nconst activeLineHighlighter = /*@__PURE__*/ViewPlugin.fromClass(class {\n    constructor(view) {\n        this.decorations = this.getDeco(view);\n    }\n    update(update) {\n        if (update.docChanged || update.selectionSet)\n            this.decorations = this.getDeco(update.view);\n    }\n    getDeco(view) {\n        let lastLineStart = -1, deco = [];\n        for (let r of view.state.selection.ranges) {\n            let line = view.lineBlockAt(r.head);\n            if (line.from > lastLineStart) {\n                deco.push(lineDeco.range(line.from));\n                lastLineStart = line.from;\n            }\n        }\n        return Decoration.set(deco);\n    }\n}, {\n    decorations: v => v.decorations\n});\n\nclass Placeholder extends WidgetType {\n    constructor(content) {\n        super();\n        this.content = content;\n    }\n    toDOM() {\n        let wrap = document.createElement(\"span\");\n        wrap.className = \"cm-placeholder\";\n        wrap.style.pointerEvents = \"none\";\n        wrap.appendChild(typeof this.content == \"string\" ? document.createTextNode(this.content) : this.content);\n        if (typeof this.content == \"string\")\n            wrap.setAttribute(\"aria-label\", \"placeholder \" + this.content);\n        else\n            wrap.setAttribute(\"aria-hidden\", \"true\");\n        return wrap;\n    }\n    coordsAt(dom) {\n        let rects = dom.firstChild ? clientRectsFor(dom.firstChild) : [];\n        if (!rects.length)\n            return null;\n        let style = window.getComputedStyle(dom.parentNode);\n        let rect = flattenRect(rects[0], style.direction != \"rtl\");\n        let lineHeight = parseInt(style.lineHeight);\n        if (rect.bottom - rect.top > lineHeight * 1.5)\n            return { left: rect.left, right: rect.right, top: rect.top, bottom: rect.top + lineHeight };\n        return rect;\n    }\n    ignoreEvent() { return false; }\n}\n/**\nExtension that enables a placeholder—a piece of example content\nto show when the editor is empty.\n*/\nfunction placeholder(content) {\n    return ViewPlugin.fromClass(class {\n        constructor(view) {\n            this.view = view;\n            this.placeholder = content\n                ? Decoration.set([Decoration.widget({ widget: new Placeholder(content), side: 1 }).range(0)])\n                : Decoration.none;\n        }\n        get decorations() { return this.view.state.doc.length ? Decoration.none : this.placeholder; }\n    }, { decorations: v => v.decorations });\n}\n\n// Don't compute precise column positions for line offsets above this\n// (since it could get expensive). Assume offset==column for them.\nconst MaxOff = 2000;\nfunction rectangleFor(state, a, b) {\n    let startLine = Math.min(a.line, b.line), endLine = Math.max(a.line, b.line);\n    let ranges = [];\n    if (a.off > MaxOff || b.off > MaxOff || a.col < 0 || b.col < 0) {\n        let startOff = Math.min(a.off, b.off), endOff = Math.max(a.off, b.off);\n        for (let i = startLine; i <= endLine; i++) {\n            let line = state.doc.line(i);\n            if (line.length <= endOff)\n                ranges.push(_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.EditorSelection.range(line.from + startOff, line.to + endOff));\n        }\n    }\n    else {\n        let startCol = Math.min(a.col, b.col), endCol = Math.max(a.col, b.col);\n        for (let i = startLine; i <= endLine; i++) {\n            let line = state.doc.line(i);\n            let start = (0,_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.findColumn)(line.text, startCol, state.tabSize, true);\n            if (start < 0) {\n                ranges.push(_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.EditorSelection.cursor(line.to));\n            }\n            else {\n                let end = (0,_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.findColumn)(line.text, endCol, state.tabSize);\n                ranges.push(_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.EditorSelection.range(line.from + start, line.from + end));\n            }\n        }\n    }\n    return ranges;\n}\nfunction absoluteColumn(view, x) {\n    let ref = view.coordsAtPos(view.viewport.from);\n    return ref ? Math.round(Math.abs((ref.left - x) / view.defaultCharacterWidth)) : -1;\n}\nfunction getPos(view, event) {\n    let offset = view.posAtCoords({ x: event.clientX, y: event.clientY }, false);\n    let line = view.state.doc.lineAt(offset), off = offset - line.from;\n    let col = off > MaxOff ? -1\n        : off == line.length ? absoluteColumn(view, event.clientX)\n            : (0,_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.countColumn)(line.text, view.state.tabSize, offset - line.from);\n    return { line: line.number, col, off };\n}\nfunction rectangleSelectionStyle(view, event) {\n    let start = getPos(view, event), startSel = view.state.selection;\n    if (!start)\n        return null;\n    return {\n        update(update) {\n            if (update.docChanged) {\n                let newStart = update.changes.mapPos(update.startState.doc.line(start.line).from);\n                let newLine = update.state.doc.lineAt(newStart);\n                start = { line: newLine.number, col: start.col, off: Math.min(start.off, newLine.length) };\n                startSel = startSel.map(update.changes);\n            }\n        },\n        get(event, _extend, multiple) {\n            let cur = getPos(view, event);\n            if (!cur)\n                return startSel;\n            let ranges = rectangleFor(view.state, start, cur);\n            if (!ranges.length)\n                return startSel;\n            if (multiple)\n                return _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.EditorSelection.create(ranges.concat(startSel.ranges));\n            else\n                return _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.EditorSelection.create(ranges);\n        }\n    };\n}\n/**\nCreate an extension that enables rectangular selections. By\ndefault, it will react to left mouse drag with the Alt key held\ndown. When such a selection occurs, the text within the rectangle\nthat was dragged over will be selected, as one selection\n[range](https://codemirror.net/6/docs/ref/#state.SelectionRange) per line.\n*/\nfunction rectangularSelection(options) {\n    let filter = (options === null || options === void 0 ? void 0 : options.eventFilter) || (e => e.altKey && e.button == 0);\n    return EditorView.mouseSelectionStyle.of((view, event) => filter(event) ? rectangleSelectionStyle(view, event) : null);\n}\nconst keys = {\n    Alt: [18, e => !!e.altKey],\n    Control: [17, e => !!e.ctrlKey],\n    Shift: [16, e => !!e.shiftKey],\n    Meta: [91, e => !!e.metaKey]\n};\nconst showCrosshair = { style: \"cursor: crosshair\" };\n/**\nReturns an extension that turns the pointer cursor into a\ncrosshair when a given modifier key, defaulting to Alt, is held\ndown. Can serve as a visual hint that rectangular selection is\ngoing to happen when paired with\n[`rectangularSelection`](https://codemirror.net/6/docs/ref/#view.rectangularSelection).\n*/\nfunction crosshairCursor(options = {}) {\n    let [code, getter] = keys[options.key || \"Alt\"];\n    let plugin = ViewPlugin.fromClass(class {\n        constructor(view) {\n            this.view = view;\n            this.isDown = false;\n        }\n        set(isDown) {\n            if (this.isDown != isDown) {\n                this.isDown = isDown;\n                this.view.update([]);\n            }\n        }\n    }, {\n        eventObservers: {\n            keydown(e) {\n                this.set(e.keyCode == code || getter(e));\n            },\n            keyup(e) {\n                if (e.keyCode == code || !getter(e))\n                    this.set(false);\n            },\n            mousemove(e) {\n                this.set(getter(e));\n            }\n        }\n    });\n    return [\n        plugin,\n        EditorView.contentAttributes.of(view => { var _a; return ((_a = view.plugin(plugin)) === null || _a === void 0 ? void 0 : _a.isDown) ? showCrosshair : null; })\n    ];\n}\n\nconst Outside = \"-10000px\";\nclass TooltipViewManager {\n    constructor(view, facet, createTooltipView, removeTooltipView) {\n        this.facet = facet;\n        this.createTooltipView = createTooltipView;\n        this.removeTooltipView = removeTooltipView;\n        this.input = view.state.facet(facet);\n        this.tooltips = this.input.filter(t => t);\n        let prev = null;\n        this.tooltipViews = this.tooltips.map(t => prev = createTooltipView(t, prev));\n    }\n    update(update, above) {\n        var _a;\n        let input = update.state.facet(this.facet);\n        let tooltips = input.filter(x => x);\n        if (input === this.input) {\n            for (let t of this.tooltipViews)\n                if (t.update)\n                    t.update(update);\n            return false;\n        }\n        let tooltipViews = [], newAbove = above ? [] : null;\n        for (let i = 0; i < tooltips.length; i++) {\n            let tip = tooltips[i], known = -1;\n            if (!tip)\n                continue;\n            for (let i = 0; i < this.tooltips.length; i++) {\n                let other = this.tooltips[i];\n                if (other && other.create == tip.create)\n                    known = i;\n            }\n            if (known < 0) {\n                tooltipViews[i] = this.createTooltipView(tip, i ? tooltipViews[i - 1] : null);\n                if (newAbove)\n                    newAbove[i] = !!tip.above;\n            }\n            else {\n                let tooltipView = tooltipViews[i] = this.tooltipViews[known];\n                if (newAbove)\n                    newAbove[i] = above[known];\n                if (tooltipView.update)\n                    tooltipView.update(update);\n            }\n        }\n        for (let t of this.tooltipViews)\n            if (tooltipViews.indexOf(t) < 0) {\n                this.removeTooltipView(t);\n                (_a = t.destroy) === null || _a === void 0 ? void 0 : _a.call(t);\n            }\n        if (above) {\n            newAbove.forEach((val, i) => above[i] = val);\n            above.length = newAbove.length;\n        }\n        this.input = input;\n        this.tooltips = tooltips;\n        this.tooltipViews = tooltipViews;\n        return true;\n    }\n}\n/**\nCreates an extension that configures tooltip behavior.\n*/\nfunction tooltips(config = {}) {\n    return tooltipConfig.of(config);\n}\nfunction windowSpace(view) {\n    let { win } = view;\n    return { top: 0, left: 0, bottom: win.innerHeight, right: win.innerWidth };\n}\nconst tooltipConfig = /*@__PURE__*/_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.Facet.define({\n    combine: values => {\n        var _a, _b, _c;\n        return ({\n            position: browser.ios ? \"absolute\" : ((_a = values.find(conf => conf.position)) === null || _a === void 0 ? void 0 : _a.position) || \"fixed\",\n            parent: ((_b = values.find(conf => conf.parent)) === null || _b === void 0 ? void 0 : _b.parent) || null,\n            tooltipSpace: ((_c = values.find(conf => conf.tooltipSpace)) === null || _c === void 0 ? void 0 : _c.tooltipSpace) || windowSpace,\n        });\n    }\n});\nconst knownHeight = /*@__PURE__*/new WeakMap();\nconst tooltipPlugin = /*@__PURE__*/ViewPlugin.fromClass(class {\n    constructor(view) {\n        this.view = view;\n        this.above = [];\n        this.inView = true;\n        this.madeAbsolute = false;\n        this.lastTransaction = 0;\n        this.measureTimeout = -1;\n        let config = view.state.facet(tooltipConfig);\n        this.position = config.position;\n        this.parent = config.parent;\n        this.classes = view.themeClasses;\n        this.createContainer();\n        this.measureReq = { read: this.readMeasure.bind(this), write: this.writeMeasure.bind(this), key: this };\n        this.resizeObserver = typeof ResizeObserver == \"function\" ? new ResizeObserver(() => this.measureSoon()) : null;\n        this.manager = new TooltipViewManager(view, showTooltip, (t, p) => this.createTooltip(t, p), t => {\n            if (this.resizeObserver)\n                this.resizeObserver.unobserve(t.dom);\n            t.dom.remove();\n        });\n        this.above = this.manager.tooltips.map(t => !!t.above);\n        this.intersectionObserver = typeof IntersectionObserver == \"function\" ? new IntersectionObserver(entries => {\n            if (Date.now() > this.lastTransaction - 50 &&\n                entries.length > 0 && entries[entries.length - 1].intersectionRatio < 1)\n                this.measureSoon();\n        }, { threshold: [1] }) : null;\n        this.observeIntersection();\n        view.win.addEventListener(\"resize\", this.measureSoon = this.measureSoon.bind(this));\n        this.maybeMeasure();\n    }\n    createContainer() {\n        if (this.parent) {\n            this.container = document.createElement(\"div\");\n            this.container.style.position = \"relative\";\n            this.container.className = this.view.themeClasses;\n            this.parent.appendChild(this.container);\n        }\n        else {\n            this.container = this.view.dom;\n        }\n    }\n    observeIntersection() {\n        if (this.intersectionObserver) {\n            this.intersectionObserver.disconnect();\n            for (let tooltip of this.manager.tooltipViews)\n                this.intersectionObserver.observe(tooltip.dom);\n        }\n    }\n    measureSoon() {\n        if (this.measureTimeout < 0)\n            this.measureTimeout = setTimeout(() => {\n                this.measureTimeout = -1;\n                this.maybeMeasure();\n            }, 50);\n    }\n    update(update) {\n        if (update.transactions.length)\n            this.lastTransaction = Date.now();\n        let updated = this.manager.update(update, this.above);\n        if (updated)\n            this.observeIntersection();\n        let shouldMeasure = updated || update.geometryChanged;\n        let newConfig = update.state.facet(tooltipConfig);\n        if (newConfig.position != this.position && !this.madeAbsolute) {\n            this.position = newConfig.position;\n            for (let t of this.manager.tooltipViews)\n                t.dom.style.position = this.position;\n            shouldMeasure = true;\n        }\n        if (newConfig.parent != this.parent) {\n            if (this.parent)\n                this.container.remove();\n            this.parent = newConfig.parent;\n            this.createContainer();\n            for (let t of this.manager.tooltipViews)\n                this.container.appendChild(t.dom);\n            shouldMeasure = true;\n        }\n        else if (this.parent && this.view.themeClasses != this.classes) {\n            this.classes = this.container.className = this.view.themeClasses;\n        }\n        if (shouldMeasure)\n            this.maybeMeasure();\n    }\n    createTooltip(tooltip, prev) {\n        let tooltipView = tooltip.create(this.view);\n        let before = prev ? prev.dom : null;\n        tooltipView.dom.classList.add(\"cm-tooltip\");\n        if (tooltip.arrow && !tooltipView.dom.querySelector(\".cm-tooltip > .cm-tooltip-arrow\")) {\n            let arrow = document.createElement(\"div\");\n            arrow.className = \"cm-tooltip-arrow\";\n            tooltipView.dom.appendChild(arrow);\n        }\n        tooltipView.dom.style.position = this.position;\n        tooltipView.dom.style.top = Outside;\n        tooltipView.dom.style.left = \"0px\";\n        this.container.insertBefore(tooltipView.dom, before);\n        if (tooltipView.mount)\n            tooltipView.mount(this.view);\n        if (this.resizeObserver)\n            this.resizeObserver.observe(tooltipView.dom);\n        return tooltipView;\n    }\n    destroy() {\n        var _a, _b, _c;\n        this.view.win.removeEventListener(\"resize\", this.measureSoon);\n        for (let tooltipView of this.manager.tooltipViews) {\n            tooltipView.dom.remove();\n            (_a = tooltipView.destroy) === null || _a === void 0 ? void 0 : _a.call(tooltipView);\n        }\n        if (this.parent)\n            this.container.remove();\n        (_b = this.resizeObserver) === null || _b === void 0 ? void 0 : _b.disconnect();\n        (_c = this.intersectionObserver) === null || _c === void 0 ? void 0 : _c.disconnect();\n        clearTimeout(this.measureTimeout);\n    }\n    readMeasure() {\n        let editor = this.view.dom.getBoundingClientRect();\n        let scaleX = 1, scaleY = 1, makeAbsolute = false;\n        if (this.position == \"fixed\" && this.manager.tooltipViews.length) {\n            let { dom } = this.manager.tooltipViews[0];\n            if (browser.gecko) {\n                // Firefox sets the element's `offsetParent` to the\n                // transformed element when a transform interferes with fixed\n                // positioning.\n                makeAbsolute = dom.offsetParent != this.container.ownerDocument.body;\n            }\n            else if (dom.style.top == Outside && dom.style.left == \"0px\") {\n                // On other browsers, we have to awkwardly try and use other\n                // information to detect a transform.\n                let rect = dom.getBoundingClientRect();\n                makeAbsolute = Math.abs(rect.top + 10000) > 1 || Math.abs(rect.left) > 1;\n            }\n        }\n        if (makeAbsolute || this.position == \"absolute\") {\n            if (this.parent) {\n                let rect = this.parent.getBoundingClientRect();\n                if (rect.width && rect.height) {\n                    scaleX = rect.width / this.parent.offsetWidth;\n                    scaleY = rect.height / this.parent.offsetHeight;\n                }\n            }\n            else {\n                ({ scaleX, scaleY } = this.view.viewState);\n            }\n        }\n        return {\n            editor,\n            parent: this.parent ? this.container.getBoundingClientRect() : editor,\n            pos: this.manager.tooltips.map((t, i) => {\n                let tv = this.manager.tooltipViews[i];\n                return tv.getCoords ? tv.getCoords(t.pos) : this.view.coordsAtPos(t.pos);\n            }),\n            size: this.manager.tooltipViews.map(({ dom }) => dom.getBoundingClientRect()),\n            space: this.view.state.facet(tooltipConfig).tooltipSpace(this.view),\n            scaleX, scaleY, makeAbsolute\n        };\n    }\n    writeMeasure(measured) {\n        var _a;\n        if (measured.makeAbsolute) {\n            this.madeAbsolute = true;\n            this.position = \"absolute\";\n            for (let t of this.manager.tooltipViews)\n                t.dom.style.position = \"absolute\";\n        }\n        let { editor, space, scaleX, scaleY } = measured;\n        let others = [];\n        for (let i = 0; i < this.manager.tooltips.length; i++) {\n            let tooltip = this.manager.tooltips[i], tView = this.manager.tooltipViews[i], { dom } = tView;\n            let pos = measured.pos[i], size = measured.size[i];\n            // Hide tooltips that are outside of the editor.\n            if (!pos || pos.bottom <= Math.max(editor.top, space.top) ||\n                pos.top >= Math.min(editor.bottom, space.bottom) ||\n                pos.right < Math.max(editor.left, space.left) - .1 ||\n                pos.left > Math.min(editor.right, space.right) + .1) {\n                dom.style.top = Outside;\n                continue;\n            }\n            let arrow = tooltip.arrow ? tView.dom.querySelector(\".cm-tooltip-arrow\") : null;\n            let arrowHeight = arrow ? 7 /* Arrow.Size */ : 0;\n            let width = size.right - size.left, height = (_a = knownHeight.get(tView)) !== null && _a !== void 0 ? _a : size.bottom - size.top;\n            let offset = tView.offset || noOffset, ltr = this.view.textDirection == Direction.LTR;\n            let left = size.width > space.right - space.left ? (ltr ? space.left : space.right - size.width)\n                : ltr ? Math.min(pos.left - (arrow ? 14 /* Arrow.Offset */ : 0) + offset.x, space.right - width)\n                    : Math.max(space.left, pos.left - width + (arrow ? 14 /* Arrow.Offset */ : 0) - offset.x);\n            let above = this.above[i];\n            if (!tooltip.strictSide && (above\n                ? pos.top - (size.bottom - size.top) - offset.y < space.top\n                : pos.bottom + (size.bottom - size.top) + offset.y > space.bottom) &&\n                above == (space.bottom - pos.bottom > pos.top - space.top))\n                above = this.above[i] = !above;\n            let spaceVert = (above ? pos.top - space.top : space.bottom - pos.bottom) - arrowHeight;\n            if (spaceVert < height && tView.resize !== false) {\n                if (spaceVert < this.view.defaultLineHeight) {\n                    dom.style.top = Outside;\n                    continue;\n                }\n                knownHeight.set(tView, height);\n                dom.style.height = (height = spaceVert) / scaleY + \"px\";\n            }\n            else if (dom.style.height) {\n                dom.style.height = \"\";\n            }\n            let top = above ? pos.top - height - arrowHeight - offset.y : pos.bottom + arrowHeight + offset.y;\n            let right = left + width;\n            if (tView.overlap !== true)\n                for (let r of others)\n                    if (r.left < right && r.right > left && r.top < top + height && r.bottom > top)\n                        top = above ? r.top - height - 2 - arrowHeight : r.bottom + arrowHeight + 2;\n            if (this.position == \"absolute\") {\n                dom.style.top = (top - measured.parent.top) / scaleY + \"px\";\n                dom.style.left = (left - measured.parent.left) / scaleX + \"px\";\n            }\n            else {\n                dom.style.top = top / scaleY + \"px\";\n                dom.style.left = left / scaleX + \"px\";\n            }\n            if (arrow) {\n                let arrowLeft = pos.left + (ltr ? offset.x : -offset.x) - (left + 14 /* Arrow.Offset */ - 7 /* Arrow.Size */);\n                arrow.style.left = arrowLeft / scaleX + \"px\";\n            }\n            if (tView.overlap !== true)\n                others.push({ left, top, right, bottom: top + height });\n            dom.classList.toggle(\"cm-tooltip-above\", above);\n            dom.classList.toggle(\"cm-tooltip-below\", !above);\n            if (tView.positioned)\n                tView.positioned(measured.space);\n        }\n    }\n    maybeMeasure() {\n        if (this.manager.tooltips.length) {\n            if (this.view.inView)\n                this.view.requestMeasure(this.measureReq);\n            if (this.inView != this.view.inView) {\n                this.inView = this.view.inView;\n                if (!this.inView)\n                    for (let tv of this.manager.tooltipViews)\n                        tv.dom.style.top = Outside;\n            }\n        }\n    }\n}, {\n    eventObservers: {\n        scroll() { this.maybeMeasure(); }\n    }\n});\nconst baseTheme = /*@__PURE__*/EditorView.baseTheme({\n    \".cm-tooltip\": {\n        zIndex: 100,\n        boxSizing: \"border-box\"\n    },\n    \"&light .cm-tooltip\": {\n        border: \"1px solid #bbb\",\n        backgroundColor: \"#f5f5f5\"\n    },\n    \"&light .cm-tooltip-section:not(:first-child)\": {\n        borderTop: \"1px solid #bbb\",\n    },\n    \"&dark .cm-tooltip\": {\n        backgroundColor: \"#333338\",\n        color: \"white\"\n    },\n    \".cm-tooltip-arrow\": {\n        height: `${7 /* Arrow.Size */}px`,\n        width: `${7 /* Arrow.Size */ * 2}px`,\n        position: \"absolute\",\n        zIndex: -1,\n        overflow: \"hidden\",\n        \"&:before, &:after\": {\n            content: \"''\",\n            position: \"absolute\",\n            width: 0,\n            height: 0,\n            borderLeft: `${7 /* Arrow.Size */}px solid transparent`,\n            borderRight: `${7 /* Arrow.Size */}px solid transparent`,\n        },\n        \".cm-tooltip-above &\": {\n            bottom: `-${7 /* Arrow.Size */}px`,\n            \"&:before\": {\n                borderTop: `${7 /* Arrow.Size */}px solid #bbb`,\n            },\n            \"&:after\": {\n                borderTop: `${7 /* Arrow.Size */}px solid #f5f5f5`,\n                bottom: \"1px\"\n            }\n        },\n        \".cm-tooltip-below &\": {\n            top: `-${7 /* Arrow.Size */}px`,\n            \"&:before\": {\n                borderBottom: `${7 /* Arrow.Size */}px solid #bbb`,\n            },\n            \"&:after\": {\n                borderBottom: `${7 /* Arrow.Size */}px solid #f5f5f5`,\n                top: \"1px\"\n            }\n        },\n    },\n    \"&dark .cm-tooltip .cm-tooltip-arrow\": {\n        \"&:before\": {\n            borderTopColor: \"#333338\",\n            borderBottomColor: \"#333338\"\n        },\n        \"&:after\": {\n            borderTopColor: \"transparent\",\n            borderBottomColor: \"transparent\"\n        }\n    }\n});\nconst noOffset = { x: 0, y: 0 };\n/**\nFacet to which an extension can add a value to show a tooltip.\n*/\nconst showTooltip = /*@__PURE__*/_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.Facet.define({\n    enables: [tooltipPlugin, baseTheme]\n});\nconst showHoverTooltip = /*@__PURE__*/_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.Facet.define({\n    combine: inputs => inputs.reduce((a, i) => a.concat(i), [])\n});\nclass HoverTooltipHost {\n    // Needs to be static so that host tooltip instances always match\n    static create(view) {\n        return new HoverTooltipHost(view);\n    }\n    constructor(view) {\n        this.view = view;\n        this.mounted = false;\n        this.dom = document.createElement(\"div\");\n        this.dom.classList.add(\"cm-tooltip-hover\");\n        this.manager = new TooltipViewManager(view, showHoverTooltip, (t, p) => this.createHostedView(t, p), t => t.dom.remove());\n    }\n    createHostedView(tooltip, prev) {\n        let hostedView = tooltip.create(this.view);\n        hostedView.dom.classList.add(\"cm-tooltip-section\");\n        this.dom.insertBefore(hostedView.dom, prev ? prev.dom.nextSibling : this.dom.firstChild);\n        if (this.mounted && hostedView.mount)\n            hostedView.mount(this.view);\n        return hostedView;\n    }\n    mount(view) {\n        for (let hostedView of this.manager.tooltipViews) {\n            if (hostedView.mount)\n                hostedView.mount(view);\n        }\n        this.mounted = true;\n    }\n    positioned(space) {\n        for (let hostedView of this.manager.tooltipViews) {\n            if (hostedView.positioned)\n                hostedView.positioned(space);\n        }\n    }\n    update(update) {\n        this.manager.update(update);\n    }\n    destroy() {\n        var _a;\n        for (let t of this.manager.tooltipViews)\n            (_a = t.destroy) === null || _a === void 0 ? void 0 : _a.call(t);\n    }\n    passProp(name) {\n        let value = undefined;\n        for (let view of this.manager.tooltipViews) {\n            let given = view[name];\n            if (given !== undefined) {\n                if (value === undefined)\n                    value = given;\n                else if (value !== given)\n                    return undefined;\n            }\n        }\n        return value;\n    }\n    get offset() { return this.passProp(\"offset\"); }\n    get getCoords() { return this.passProp(\"getCoords\"); }\n    get overlap() { return this.passProp(\"overlap\"); }\n    get resize() { return this.passProp(\"resize\"); }\n}\nconst showHoverTooltipHost = /*@__PURE__*/showTooltip.compute([showHoverTooltip], state => {\n    let tooltips = state.facet(showHoverTooltip);\n    if (tooltips.length === 0)\n        return null;\n    return {\n        pos: Math.min(...tooltips.map(t => t.pos)),\n        end: Math.max(...tooltips.map(t => { var _a; return (_a = t.end) !== null && _a !== void 0 ? _a : t.pos; })),\n        create: HoverTooltipHost.create,\n        above: tooltips[0].above,\n        arrow: tooltips.some(t => t.arrow),\n    };\n});\nclass HoverPlugin {\n    constructor(view, source, field, setHover, hoverTime) {\n        this.view = view;\n        this.source = source;\n        this.field = field;\n        this.setHover = setHover;\n        this.hoverTime = hoverTime;\n        this.hoverTimeout = -1;\n        this.restartTimeout = -1;\n        this.pending = null;\n        this.lastMove = { x: 0, y: 0, target: view.dom, time: 0 };\n        this.checkHover = this.checkHover.bind(this);\n        view.dom.addEventListener(\"mouseleave\", this.mouseleave = this.mouseleave.bind(this));\n        view.dom.addEventListener(\"mousemove\", this.mousemove = this.mousemove.bind(this));\n    }\n    update() {\n        if (this.pending) {\n            this.pending = null;\n            clearTimeout(this.restartTimeout);\n            this.restartTimeout = setTimeout(() => this.startHover(), 20);\n        }\n    }\n    get active() {\n        return this.view.state.field(this.field);\n    }\n    checkHover() {\n        this.hoverTimeout = -1;\n        if (this.active.length)\n            return;\n        let hovered = Date.now() - this.lastMove.time;\n        if (hovered < this.hoverTime)\n            this.hoverTimeout = setTimeout(this.checkHover, this.hoverTime - hovered);\n        else\n            this.startHover();\n    }\n    startHover() {\n        clearTimeout(this.restartTimeout);\n        let { view, lastMove } = this;\n        let desc = view.docView.nearest(lastMove.target);\n        if (!desc)\n            return;\n        let pos, side = 1;\n        if (desc instanceof WidgetView) {\n            pos = desc.posAtStart;\n        }\n        else {\n            pos = view.posAtCoords(lastMove);\n            if (pos == null)\n                return;\n            let posCoords = view.coordsAtPos(pos);\n            if (!posCoords ||\n                lastMove.y < posCoords.top || lastMove.y > posCoords.bottom ||\n                lastMove.x < posCoords.left - view.defaultCharacterWidth ||\n                lastMove.x > posCoords.right + view.defaultCharacterWidth)\n                return;\n            let bidi = view.bidiSpans(view.state.doc.lineAt(pos)).find(s => s.from <= pos && s.to >= pos);\n            let rtl = bidi && bidi.dir == Direction.RTL ? -1 : 1;\n            side = (lastMove.x < posCoords.left ? -rtl : rtl);\n        }\n        let open = this.source(view, pos, side);\n        if (open === null || open === void 0 ? void 0 : open.then) {\n            let pending = this.pending = { pos };\n            open.then(result => {\n                if (this.pending == pending) {\n                    this.pending = null;\n                    if (result && !(Array.isArray(result) && !result.length))\n                        view.dispatch({ effects: this.setHover.of(Array.isArray(result) ? result : [result]) });\n                }\n            }, e => logException(view.state, e, \"hover tooltip\"));\n        }\n        else if (open && !(Array.isArray(open) && !open.length)) {\n            view.dispatch({ effects: this.setHover.of(Array.isArray(open) ? open : [open]) });\n        }\n    }\n    get tooltip() {\n        let plugin = this.view.plugin(tooltipPlugin);\n        let index = plugin ? plugin.manager.tooltips.findIndex(t => t.create == HoverTooltipHost.create) : -1;\n        return index > -1 ? plugin.manager.tooltipViews[index] : null;\n    }\n    mousemove(event) {\n        var _a, _b;\n        this.lastMove = { x: event.clientX, y: event.clientY, target: event.target, time: Date.now() };\n        if (this.hoverTimeout < 0)\n            this.hoverTimeout = setTimeout(this.checkHover, this.hoverTime);\n        let { active, tooltip } = this;\n        if (active.length && tooltip && !isInTooltip(tooltip.dom, event) || this.pending) {\n            let { pos } = active[0] || this.pending, end = (_b = (_a = active[0]) === null || _a === void 0 ? void 0 : _a.end) !== null && _b !== void 0 ? _b : pos;\n            if ((pos == end ? this.view.posAtCoords(this.lastMove) != pos\n                : !isOverRange(this.view, pos, end, event.clientX, event.clientY))) {\n                this.view.dispatch({ effects: this.setHover.of([]) });\n                this.pending = null;\n            }\n        }\n    }\n    mouseleave(event) {\n        clearTimeout(this.hoverTimeout);\n        this.hoverTimeout = -1;\n        let { active } = this;\n        if (active.length) {\n            let { tooltip } = this;\n            let inTooltip = tooltip && tooltip.dom.contains(event.relatedTarget);\n            if (!inTooltip)\n                this.view.dispatch({ effects: this.setHover.of([]) });\n            else\n                this.watchTooltipLeave(tooltip.dom);\n        }\n    }\n    watchTooltipLeave(tooltip) {\n        let watch = (event) => {\n            tooltip.removeEventListener(\"mouseleave\", watch);\n            if (this.active.length && !this.view.dom.contains(event.relatedTarget))\n                this.view.dispatch({ effects: this.setHover.of([]) });\n        };\n        tooltip.addEventListener(\"mouseleave\", watch);\n    }\n    destroy() {\n        clearTimeout(this.hoverTimeout);\n        this.view.dom.removeEventListener(\"mouseleave\", this.mouseleave);\n        this.view.dom.removeEventListener(\"mousemove\", this.mousemove);\n    }\n}\nconst tooltipMargin = 4;\nfunction isInTooltip(tooltip, event) {\n    let rect = tooltip.getBoundingClientRect();\n    return event.clientX >= rect.left - tooltipMargin && event.clientX <= rect.right + tooltipMargin &&\n        event.clientY >= rect.top - tooltipMargin && event.clientY <= rect.bottom + tooltipMargin;\n}\nfunction isOverRange(view, from, to, x, y, margin) {\n    let rect = view.scrollDOM.getBoundingClientRect();\n    let docBottom = view.documentTop + view.documentPadding.top + view.contentHeight;\n    if (rect.left > x || rect.right < x || rect.top > y || Math.min(rect.bottom, docBottom) < y)\n        return false;\n    let pos = view.posAtCoords({ x, y }, false);\n    return pos >= from && pos <= to;\n}\n/**\nSet up a hover tooltip, which shows up when the pointer hovers\nover ranges of text. The callback is called when the mouse hovers\nover the document text. It should, if there is a tooltip\nassociated with position `pos`, return the tooltip description\n(either directly or in a promise). The `side` argument indicates\non which side of the position the pointer is—it will be -1 if the\npointer is before the position, 1 if after the position.\n\nNote that all hover tooltips are hosted within a single tooltip\ncontainer element. This allows multiple tooltips over the same\nrange to be \"merged\" together without overlapping.\n*/\nfunction hoverTooltip(source, options = {}) {\n    let setHover = _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.StateEffect.define();\n    let hoverState = _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.StateField.define({\n        create() { return []; },\n        update(value, tr) {\n            if (value.length) {\n                if (options.hideOnChange && (tr.docChanged || tr.selection))\n                    value = [];\n                else if (options.hideOn)\n                    value = value.filter(v => !options.hideOn(tr, v));\n                if (tr.docChanged) {\n                    let mapped = [];\n                    for (let tooltip of value) {\n                        let newPos = tr.changes.mapPos(tooltip.pos, -1, _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.MapMode.TrackDel);\n                        if (newPos != null) {\n                            let copy = Object.assign(Object.create(null), tooltip);\n                            copy.pos = newPos;\n                            if (copy.end != null)\n                                copy.end = tr.changes.mapPos(copy.end);\n                            mapped.push(copy);\n                        }\n                    }\n                    value = mapped;\n                }\n            }\n            for (let effect of tr.effects) {\n                if (effect.is(setHover))\n                    value = effect.value;\n                if (effect.is(closeHoverTooltipEffect))\n                    value = [];\n            }\n            return value;\n        },\n        provide: f => showHoverTooltip.from(f)\n    });\n    return [\n        hoverState,\n        ViewPlugin.define(view => new HoverPlugin(view, source, hoverState, setHover, options.hoverTime || 300 /* Hover.Time */)),\n        showHoverTooltipHost\n    ];\n}\n/**\nGet the active tooltip view for a given tooltip, if available.\n*/\nfunction getTooltip(view, tooltip) {\n    let plugin = view.plugin(tooltipPlugin);\n    if (!plugin)\n        return null;\n    let found = plugin.manager.tooltips.indexOf(tooltip);\n    return found < 0 ? null : plugin.manager.tooltipViews[found];\n}\n/**\nReturns true if any hover tooltips are currently active.\n*/\nfunction hasHoverTooltips(state) {\n    return state.facet(showHoverTooltip).some(x => x);\n}\nconst closeHoverTooltipEffect = /*@__PURE__*/_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.StateEffect.define();\n/**\nTransaction effect that closes all hover tooltips.\n*/\nconst closeHoverTooltips = /*@__PURE__*/closeHoverTooltipEffect.of(null);\n/**\nTell the tooltip extension to recompute the position of the active\ntooltips. This can be useful when something happens (such as a\nre-positioning or CSS change affecting the editor) that could\ninvalidate the existing tooltip positions.\n*/\nfunction repositionTooltips(view) {\n    let plugin = view.plugin(tooltipPlugin);\n    if (plugin)\n        plugin.maybeMeasure();\n}\n\nconst panelConfig = /*@__PURE__*/_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.Facet.define({\n    combine(configs) {\n        let topContainer, bottomContainer;\n        for (let c of configs) {\n            topContainer = topContainer || c.topContainer;\n            bottomContainer = bottomContainer || c.bottomContainer;\n        }\n        return { topContainer, bottomContainer };\n    }\n});\n/**\nConfigures the panel-managing extension.\n*/\nfunction panels(config) {\n    return config ? [panelConfig.of(config)] : [];\n}\n/**\nGet the active panel created by the given constructor, if any.\nThis can be useful when you need access to your panels' DOM\nstructure.\n*/\nfunction getPanel(view, panel) {\n    let plugin = view.plugin(panelPlugin);\n    let index = plugin ? plugin.specs.indexOf(panel) : -1;\n    return index > -1 ? plugin.panels[index] : null;\n}\nconst panelPlugin = /*@__PURE__*/ViewPlugin.fromClass(class {\n    constructor(view) {\n        this.input = view.state.facet(showPanel);\n        this.specs = this.input.filter(s => s);\n        this.panels = this.specs.map(spec => spec(view));\n        let conf = view.state.facet(panelConfig);\n        this.top = new PanelGroup(view, true, conf.topContainer);\n        this.bottom = new PanelGroup(view, false, conf.bottomContainer);\n        this.top.sync(this.panels.filter(p => p.top));\n        this.bottom.sync(this.panels.filter(p => !p.top));\n        for (let p of this.panels) {\n            p.dom.classList.add(\"cm-panel\");\n            if (p.mount)\n                p.mount();\n        }\n    }\n    update(update) {\n        let conf = update.state.facet(panelConfig);\n        if (this.top.container != conf.topContainer) {\n            this.top.sync([]);\n            this.top = new PanelGroup(update.view, true, conf.topContainer);\n        }\n        if (this.bottom.container != conf.bottomContainer) {\n            this.bottom.sync([]);\n            this.bottom = new PanelGroup(update.view, false, conf.bottomContainer);\n        }\n        this.top.syncClasses();\n        this.bottom.syncClasses();\n        let input = update.state.facet(showPanel);\n        if (input != this.input) {\n            let specs = input.filter(x => x);\n            let panels = [], top = [], bottom = [], mount = [];\n            for (let spec of specs) {\n                let known = this.specs.indexOf(spec), panel;\n                if (known < 0) {\n                    panel = spec(update.view);\n                    mount.push(panel);\n                }\n                else {\n                    panel = this.panels[known];\n                    if (panel.update)\n                        panel.update(update);\n                }\n                panels.push(panel);\n                (panel.top ? top : bottom).push(panel);\n            }\n            this.specs = specs;\n            this.panels = panels;\n            this.top.sync(top);\n            this.bottom.sync(bottom);\n            for (let p of mount) {\n                p.dom.classList.add(\"cm-panel\");\n                if (p.mount)\n                    p.mount();\n            }\n        }\n        else {\n            for (let p of this.panels)\n                if (p.update)\n                    p.update(update);\n        }\n    }\n    destroy() {\n        this.top.sync([]);\n        this.bottom.sync([]);\n    }\n}, {\n    provide: plugin => EditorView.scrollMargins.of(view => {\n        let value = view.plugin(plugin);\n        return value && { top: value.top.scrollMargin(), bottom: value.bottom.scrollMargin() };\n    })\n});\nclass PanelGroup {\n    constructor(view, top, container) {\n        this.view = view;\n        this.top = top;\n        this.container = container;\n        this.dom = undefined;\n        this.classes = \"\";\n        this.panels = [];\n        this.syncClasses();\n    }\n    sync(panels) {\n        for (let p of this.panels)\n            if (p.destroy && panels.indexOf(p) < 0)\n                p.destroy();\n        this.panels = panels;\n        this.syncDOM();\n    }\n    syncDOM() {\n        if (this.panels.length == 0) {\n            if (this.dom) {\n                this.dom.remove();\n                this.dom = undefined;\n            }\n            return;\n        }\n        if (!this.dom) {\n            this.dom = document.createElement(\"div\");\n            this.dom.className = this.top ? \"cm-panels cm-panels-top\" : \"cm-panels cm-panels-bottom\";\n            this.dom.style[this.top ? \"top\" : \"bottom\"] = \"0\";\n            let parent = this.container || this.view.dom;\n            parent.insertBefore(this.dom, this.top ? parent.firstChild : null);\n        }\n        let curDOM = this.dom.firstChild;\n        for (let panel of this.panels) {\n            if (panel.dom.parentNode == this.dom) {\n                while (curDOM != panel.dom)\n                    curDOM = rm(curDOM);\n                curDOM = curDOM.nextSibling;\n            }\n            else {\n                this.dom.insertBefore(panel.dom, curDOM);\n            }\n        }\n        while (curDOM)\n            curDOM = rm(curDOM);\n    }\n    scrollMargin() {\n        return !this.dom || this.container ? 0\n            : Math.max(0, this.top ?\n                this.dom.getBoundingClientRect().bottom - Math.max(0, this.view.scrollDOM.getBoundingClientRect().top) :\n                Math.min(innerHeight, this.view.scrollDOM.getBoundingClientRect().bottom) - this.dom.getBoundingClientRect().top);\n    }\n    syncClasses() {\n        if (!this.container || this.classes == this.view.themeClasses)\n            return;\n        for (let cls of this.classes.split(\" \"))\n            if (cls)\n                this.container.classList.remove(cls);\n        for (let cls of (this.classes = this.view.themeClasses).split(\" \"))\n            if (cls)\n                this.container.classList.add(cls);\n    }\n}\nfunction rm(node) {\n    let next = node.nextSibling;\n    node.remove();\n    return next;\n}\n/**\nOpening a panel is done by providing a constructor function for\nthe panel through this facet. (The panel is closed again when its\nconstructor is no longer provided.) Values of `null` are ignored.\n*/\nconst showPanel = /*@__PURE__*/_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.Facet.define({\n    enables: panelPlugin\n});\n\n/**\nA gutter marker represents a bit of information attached to a line\nin a specific gutter. Your own custom markers have to extend this\nclass.\n*/\nclass GutterMarker extends _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.RangeValue {\n    /**\n    @internal\n    */\n    compare(other) {\n        return this == other || this.constructor == other.constructor && this.eq(other);\n    }\n    /**\n    Compare this marker to another marker of the same type.\n    */\n    eq(other) { return false; }\n    /**\n    Called if the marker has a `toDOM` method and its representation\n    was removed from a gutter.\n    */\n    destroy(dom) { }\n}\nGutterMarker.prototype.elementClass = \"\";\nGutterMarker.prototype.toDOM = undefined;\nGutterMarker.prototype.mapMode = _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.MapMode.TrackBefore;\nGutterMarker.prototype.startSide = GutterMarker.prototype.endSide = -1;\nGutterMarker.prototype.point = true;\n/**\nFacet used to add a class to all gutter elements for a given line.\nMarkers given to this facet should _only_ define an\n[`elementclass`](https://codemirror.net/6/docs/ref/#view.GutterMarker.elementClass), not a\n[`toDOM`](https://codemirror.net/6/docs/ref/#view.GutterMarker.toDOM) (or the marker will appear\nin all gutters for the line).\n*/\nconst gutterLineClass = /*@__PURE__*/_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.Facet.define();\nconst defaults = {\n    class: \"\",\n    renderEmptyElements: false,\n    elementStyle: \"\",\n    markers: () => _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.RangeSet.empty,\n    lineMarker: () => null,\n    widgetMarker: () => null,\n    lineMarkerChange: null,\n    initialSpacer: null,\n    updateSpacer: null,\n    domEventHandlers: {}\n};\nconst activeGutters = /*@__PURE__*/_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.Facet.define();\n/**\nDefine an editor gutter. The order in which the gutters appear is\ndetermined by their extension priority.\n*/\nfunction gutter(config) {\n    return [gutters(), activeGutters.of(Object.assign(Object.assign({}, defaults), config))];\n}\nconst unfixGutters = /*@__PURE__*/_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.Facet.define({\n    combine: values => values.some(x => x)\n});\n/**\nThe gutter-drawing plugin is automatically enabled when you add a\ngutter, but you can use this function to explicitly configure it.\n\nUnless `fixed` is explicitly set to `false`, the gutters are\nfixed, meaning they don't scroll along with the content\nhorizontally (except on Internet Explorer, which doesn't support\nCSS [`position:\nsticky`](https://developer.mozilla.org/en-US/docs/Web/CSS/position#sticky)).\n*/\nfunction gutters(config) {\n    let result = [\n        gutterView,\n    ];\n    if (config && config.fixed === false)\n        result.push(unfixGutters.of(true));\n    return result;\n}\nconst gutterView = /*@__PURE__*/ViewPlugin.fromClass(class {\n    constructor(view) {\n        this.view = view;\n        this.prevViewport = view.viewport;\n        this.dom = document.createElement(\"div\");\n        this.dom.className = \"cm-gutters\";\n        this.dom.setAttribute(\"aria-hidden\", \"true\");\n        this.dom.style.minHeight = (this.view.contentHeight / this.view.scaleY) + \"px\";\n        this.gutters = view.state.facet(activeGutters).map(conf => new SingleGutterView(view, conf));\n        for (let gutter of this.gutters)\n            this.dom.appendChild(gutter.dom);\n        this.fixed = !view.state.facet(unfixGutters);\n        if (this.fixed) {\n            // FIXME IE11 fallback, which doesn't support position: sticky,\n            // by using position: relative + event handlers that realign the\n            // gutter (or just force fixed=false on IE11?)\n            this.dom.style.position = \"sticky\";\n        }\n        this.syncGutters(false);\n        view.scrollDOM.insertBefore(this.dom, view.contentDOM);\n    }\n    update(update) {\n        if (this.updateGutters(update)) {\n            // Detach during sync when the viewport changed significantly\n            // (such as during scrolling), since for large updates that is\n            // faster.\n            let vpA = this.prevViewport, vpB = update.view.viewport;\n            let vpOverlap = Math.min(vpA.to, vpB.to) - Math.max(vpA.from, vpB.from);\n            this.syncGutters(vpOverlap < (vpB.to - vpB.from) * 0.8);\n        }\n        if (update.geometryChanged) {\n            this.dom.style.minHeight = (this.view.contentHeight / this.view.scaleY) + \"px\";\n        }\n        if (this.view.state.facet(unfixGutters) != !this.fixed) {\n            this.fixed = !this.fixed;\n            this.dom.style.position = this.fixed ? \"sticky\" : \"\";\n        }\n        this.prevViewport = update.view.viewport;\n    }\n    syncGutters(detach) {\n        let after = this.dom.nextSibling;\n        if (detach)\n            this.dom.remove();\n        let lineClasses = _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.RangeSet.iter(this.view.state.facet(gutterLineClass), this.view.viewport.from);\n        let classSet = [];\n        let contexts = this.gutters.map(gutter => new UpdateContext(gutter, this.view.viewport, -this.view.documentPadding.top));\n        for (let line of this.view.viewportLineBlocks) {\n            if (classSet.length)\n                classSet = [];\n            if (Array.isArray(line.type)) {\n                let first = true;\n                for (let b of line.type) {\n                    if (b.type == BlockType.Text && first) {\n                        advanceCursor(lineClasses, classSet, b.from);\n                        for (let cx of contexts)\n                            cx.line(this.view, b, classSet);\n                        first = false;\n                    }\n                    else if (b.widget) {\n                        for (let cx of contexts)\n                            cx.widget(this.view, b);\n                    }\n                }\n            }\n            else if (line.type == BlockType.Text) {\n                advanceCursor(lineClasses, classSet, line.from);\n                for (let cx of contexts)\n                    cx.line(this.view, line, classSet);\n            }\n            else if (line.widget) {\n                for (let cx of contexts)\n                    cx.widget(this.view, line);\n            }\n        }\n        for (let cx of contexts)\n            cx.finish();\n        if (detach)\n            this.view.scrollDOM.insertBefore(this.dom, after);\n    }\n    updateGutters(update) {\n        let prev = update.startState.facet(activeGutters), cur = update.state.facet(activeGutters);\n        let change = update.docChanged || update.heightChanged || update.viewportChanged ||\n            !_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.RangeSet.eq(update.startState.facet(gutterLineClass), update.state.facet(gutterLineClass), update.view.viewport.from, update.view.viewport.to);\n        if (prev == cur) {\n            for (let gutter of this.gutters)\n                if (gutter.update(update))\n                    change = true;\n        }\n        else {\n            change = true;\n            let gutters = [];\n            for (let conf of cur) {\n                let known = prev.indexOf(conf);\n                if (known < 0) {\n                    gutters.push(new SingleGutterView(this.view, conf));\n                }\n                else {\n                    this.gutters[known].update(update);\n                    gutters.push(this.gutters[known]);\n                }\n            }\n            for (let g of this.gutters) {\n                g.dom.remove();\n                if (gutters.indexOf(g) < 0)\n                    g.destroy();\n            }\n            for (let g of gutters)\n                this.dom.appendChild(g.dom);\n            this.gutters = gutters;\n        }\n        return change;\n    }\n    destroy() {\n        for (let view of this.gutters)\n            view.destroy();\n        this.dom.remove();\n    }\n}, {\n    provide: plugin => EditorView.scrollMargins.of(view => {\n        let value = view.plugin(plugin);\n        if (!value || value.gutters.length == 0 || !value.fixed)\n            return null;\n        return view.textDirection == Direction.LTR\n            ? { left: value.dom.offsetWidth * view.scaleX }\n            : { right: value.dom.offsetWidth * view.scaleX };\n    })\n});\nfunction asArray(val) { return (Array.isArray(val) ? val : [val]); }\nfunction advanceCursor(cursor, collect, pos) {\n    while (cursor.value && cursor.from <= pos) {\n        if (cursor.from == pos)\n            collect.push(cursor.value);\n        cursor.next();\n    }\n}\nclass UpdateContext {\n    constructor(gutter, viewport, height) {\n        this.gutter = gutter;\n        this.height = height;\n        this.i = 0;\n        this.cursor = _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.RangeSet.iter(gutter.markers, viewport.from);\n    }\n    addElement(view, block, markers) {\n        let { gutter } = this, above = (block.top - this.height) / view.scaleY, height = block.height / view.scaleY;\n        if (this.i == gutter.elements.length) {\n            let newElt = new GutterElement(view, height, above, markers);\n            gutter.elements.push(newElt);\n            gutter.dom.appendChild(newElt.dom);\n        }\n        else {\n            gutter.elements[this.i].update(view, height, above, markers);\n        }\n        this.height = block.bottom;\n        this.i++;\n    }\n    line(view, line, extraMarkers) {\n        let localMarkers = [];\n        advanceCursor(this.cursor, localMarkers, line.from);\n        if (extraMarkers.length)\n            localMarkers = localMarkers.concat(extraMarkers);\n        let forLine = this.gutter.config.lineMarker(view, line, localMarkers);\n        if (forLine)\n            localMarkers.unshift(forLine);\n        let gutter = this.gutter;\n        if (localMarkers.length == 0 && !gutter.config.renderEmptyElements)\n            return;\n        this.addElement(view, line, localMarkers);\n    }\n    widget(view, block) {\n        let marker = this.gutter.config.widgetMarker(view, block.widget, block);\n        if (marker)\n            this.addElement(view, block, [marker]);\n    }\n    finish() {\n        let gutter = this.gutter;\n        while (gutter.elements.length > this.i) {\n            let last = gutter.elements.pop();\n            gutter.dom.removeChild(last.dom);\n            last.destroy();\n        }\n    }\n}\nclass SingleGutterView {\n    constructor(view, config) {\n        this.view = view;\n        this.config = config;\n        this.elements = [];\n        this.spacer = null;\n        this.dom = document.createElement(\"div\");\n        this.dom.className = \"cm-gutter\" + (this.config.class ? \" \" + this.config.class : \"\");\n        for (let prop in config.domEventHandlers) {\n            this.dom.addEventListener(prop, (event) => {\n                let target = event.target, y;\n                if (target != this.dom && this.dom.contains(target)) {\n                    while (target.parentNode != this.dom)\n                        target = target.parentNode;\n                    let rect = target.getBoundingClientRect();\n                    y = (rect.top + rect.bottom) / 2;\n                }\n                else {\n                    y = event.clientY;\n                }\n                let line = view.lineBlockAtHeight(y - view.documentTop);\n                if (config.domEventHandlers[prop](view, line, event))\n                    event.preventDefault();\n            });\n        }\n        this.markers = asArray(config.markers(view));\n        if (config.initialSpacer) {\n            this.spacer = new GutterElement(view, 0, 0, [config.initialSpacer(view)]);\n            this.dom.appendChild(this.spacer.dom);\n            this.spacer.dom.style.cssText += \"visibility: hidden; pointer-events: none\";\n        }\n    }\n    update(update) {\n        let prevMarkers = this.markers;\n        this.markers = asArray(this.config.markers(update.view));\n        if (this.spacer && this.config.updateSpacer) {\n            let updated = this.config.updateSpacer(this.spacer.markers[0], update);\n            if (updated != this.spacer.markers[0])\n                this.spacer.update(update.view, 0, 0, [updated]);\n        }\n        let vp = update.view.viewport;\n        return !_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.RangeSet.eq(this.markers, prevMarkers, vp.from, vp.to) ||\n            (this.config.lineMarkerChange ? this.config.lineMarkerChange(update) : false);\n    }\n    destroy() {\n        for (let elt of this.elements)\n            elt.destroy();\n    }\n}\nclass GutterElement {\n    constructor(view, height, above, markers) {\n        this.height = -1;\n        this.above = 0;\n        this.markers = [];\n        this.dom = document.createElement(\"div\");\n        this.dom.className = \"cm-gutterElement\";\n        this.update(view, height, above, markers);\n    }\n    update(view, height, above, markers) {\n        if (this.height != height) {\n            this.height = height;\n            this.dom.style.height = height + \"px\";\n        }\n        if (this.above != above)\n            this.dom.style.marginTop = (this.above = above) ? above + \"px\" : \"\";\n        if (!sameMarkers(this.markers, markers))\n            this.setMarkers(view, markers);\n    }\n    setMarkers(view, markers) {\n        let cls = \"cm-gutterElement\", domPos = this.dom.firstChild;\n        for (let iNew = 0, iOld = 0;;) {\n            let skipTo = iOld, marker = iNew < markers.length ? markers[iNew++] : null, matched = false;\n            if (marker) {\n                let c = marker.elementClass;\n                if (c)\n                    cls += \" \" + c;\n                for (let i = iOld; i < this.markers.length; i++)\n                    if (this.markers[i].compare(marker)) {\n                        skipTo = i;\n                        matched = true;\n                        break;\n                    }\n            }\n            else {\n                skipTo = this.markers.length;\n            }\n            while (iOld < skipTo) {\n                let next = this.markers[iOld++];\n                if (next.toDOM) {\n                    next.destroy(domPos);\n                    let after = domPos.nextSibling;\n                    domPos.remove();\n                    domPos = after;\n                }\n            }\n            if (!marker)\n                break;\n            if (marker.toDOM) {\n                if (matched)\n                    domPos = domPos.nextSibling;\n                else\n                    this.dom.insertBefore(marker.toDOM(view), domPos);\n            }\n            if (matched)\n                iOld++;\n        }\n        this.dom.className = cls;\n        this.markers = markers;\n    }\n    destroy() {\n        this.setMarkers(null, []); // First argument not used unless creating markers\n    }\n}\nfunction sameMarkers(a, b) {\n    if (a.length != b.length)\n        return false;\n    for (let i = 0; i < a.length; i++)\n        if (!a[i].compare(b[i]))\n            return false;\n    return true;\n}\n/**\nFacet used to provide markers to the line number gutter.\n*/\nconst lineNumberMarkers = /*@__PURE__*/_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.Facet.define();\nconst lineNumberConfig = /*@__PURE__*/_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.Facet.define({\n    combine(values) {\n        return (0,_codemirror_state__WEBPACK_IMPORTED_MODULE_2__.combineConfig)(values, { formatNumber: String, domEventHandlers: {} }, {\n            domEventHandlers(a, b) {\n                let result = Object.assign({}, a);\n                for (let event in b) {\n                    let exists = result[event], add = b[event];\n                    result[event] = exists ? (view, line, event) => exists(view, line, event) || add(view, line, event) : add;\n                }\n                return result;\n            }\n        });\n    }\n});\nclass NumberMarker extends GutterMarker {\n    constructor(number) {\n        super();\n        this.number = number;\n    }\n    eq(other) { return this.number == other.number; }\n    toDOM() { return document.createTextNode(this.number); }\n}\nfunction formatNumber(view, number) {\n    return view.state.facet(lineNumberConfig).formatNumber(number, view.state);\n}\nconst lineNumberGutter = /*@__PURE__*/activeGutters.compute([lineNumberConfig], state => ({\n    class: \"cm-lineNumbers\",\n    renderEmptyElements: false,\n    markers(view) { return view.state.facet(lineNumberMarkers); },\n    lineMarker(view, line, others) {\n        if (others.some(m => m.toDOM))\n            return null;\n        return new NumberMarker(formatNumber(view, view.state.doc.lineAt(line.from).number));\n    },\n    widgetMarker: () => null,\n    lineMarkerChange: update => update.startState.facet(lineNumberConfig) != update.state.facet(lineNumberConfig),\n    initialSpacer(view) {\n        return new NumberMarker(formatNumber(view, maxLineNumber(view.state.doc.lines)));\n    },\n    updateSpacer(spacer, update) {\n        let max = formatNumber(update.view, maxLineNumber(update.view.state.doc.lines));\n        return max == spacer.number ? spacer : new NumberMarker(max);\n    },\n    domEventHandlers: state.facet(lineNumberConfig).domEventHandlers\n}));\n/**\nCreate a line number gutter extension.\n*/\nfunction lineNumbers(config = {}) {\n    return [\n        lineNumberConfig.of(config),\n        gutters(),\n        lineNumberGutter\n    ];\n}\nfunction maxLineNumber(lines) {\n    let last = 9;\n    while (last < lines)\n        last = last * 10 + 9;\n    return last;\n}\nconst activeLineGutterMarker = /*@__PURE__*/new class extends GutterMarker {\n    constructor() {\n        super(...arguments);\n        this.elementClass = \"cm-activeLineGutter\";\n    }\n};\nconst activeLineGutterHighlighter = /*@__PURE__*/gutterLineClass.compute([\"selection\"], state => {\n    let marks = [], last = -1;\n    for (let range of state.selection.ranges) {\n        let linePos = state.doc.lineAt(range.head).from;\n        if (linePos > last) {\n            last = linePos;\n            marks.push(activeLineGutterMarker.range(linePos));\n        }\n    }\n    return _codemirror_state__WEBPACK_IMPORTED_MODULE_2__.RangeSet.of(marks);\n});\n/**\nReturns an extension that adds a `cm-activeLineGutter` class to\nall gutter elements on the [active\nline](https://codemirror.net/6/docs/ref/#view.highlightActiveLine).\n*/\nfunction highlightActiveLineGutter() {\n    return activeLineGutterHighlighter;\n}\n\nconst WhitespaceDeco = /*@__PURE__*/new Map();\nfunction getWhitespaceDeco(space) {\n    let deco = WhitespaceDeco.get(space);\n    if (!deco)\n        WhitespaceDeco.set(space, deco = Decoration.mark({\n            attributes: space === \"\\t\" ? {\n                class: \"cm-highlightTab\",\n            } : {\n                class: \"cm-highlightSpace\",\n                \"data-display\": space.replace(/ /g, \"·\")\n            }\n        }));\n    return deco;\n}\nfunction matcher(decorator) {\n    return ViewPlugin.define(view => ({\n        decorations: decorator.createDeco(view),\n        update(u) {\n            this.decorations = decorator.updateDeco(u, this.decorations);\n        },\n    }), {\n        decorations: v => v.decorations\n    });\n}\nconst whitespaceHighlighter = /*@__PURE__*/matcher(/*@__PURE__*/new MatchDecorator({\n    regexp: /\\t| +/g,\n    decoration: match => getWhitespaceDeco(match[0]),\n    boundary: /\\S/,\n}));\n/**\nReturns an extension that highlights whitespace, adding a\n`cm-highlightSpace` class to stretches of spaces, and a\n`cm-highlightTab` class to individual tab characters. By default,\nthe former are shown as faint dots, and the latter as arrows.\n*/\nfunction highlightWhitespace() {\n    return whitespaceHighlighter;\n}\nconst trailingHighlighter = /*@__PURE__*/matcher(/*@__PURE__*/new MatchDecorator({\n    regexp: /\\s+$/g,\n    decoration: /*@__PURE__*/Decoration.mark({ class: \"cm-trailingSpace\" }),\n    boundary: /\\S/,\n}));\n/**\nReturns an extension that adds a `cm-trailingSpace` class to all\ntrailing whitespace.\n*/\nfunction highlightTrailingWhitespace() {\n    return trailingHighlighter;\n}\n\n/**\n@internal\n*/\nconst __test = { HeightMap, HeightOracle, MeasuredHeights, QueryType, ChangedRange, computeOrder, moveVisually };\n\n\n\n\n//# sourceURL=webpack://_JUPYTERLAB.CORE_OUTPUT/../node_modules/@codemirror/view/dist/index.js?");

/***/ }),

/***/ "../node_modules/style-mod/src/style-mod.js":
/*!**************************************************!*\
  !*** ../node_modules/style-mod/src/style-mod.js ***!
  \**************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */   StyleModule: () => (/* binding */ StyleModule)\n/* harmony export */ });\nconst C = \"\\u037c\"\nconst COUNT = typeof Symbol == \"undefined\" ? \"__\" + C : Symbol.for(C)\nconst SET = typeof Symbol == \"undefined\" ? \"__styleSet\" + Math.floor(Math.random() * 1e8) : Symbol(\"styleSet\")\nconst top = typeof globalThis != \"undefined\" ? globalThis : typeof window != \"undefined\" ? window : {}\n\n// :: - Style modules encapsulate a set of CSS rules defined from\n// JavaScript. Their definitions are only available in a given DOM\n// root after it has been _mounted_ there with `StyleModule.mount`.\n//\n// Style modules should be created once and stored somewhere, as\n// opposed to re-creating them every time you need them. The amount of\n// CSS rules generated for a given DOM root is bounded by the amount\n// of style modules that were used. So to avoid leaking rules, don't\n// create these dynamically, but treat them as one-time allocations.\nclass StyleModule {\n  // :: (Object<Style>, ?{finish: ?(string) → string})\n  // Create a style module from the given spec.\n  //\n  // When `finish` is given, it is called on regular (non-`@`)\n  // selectors (after `&` expansion) to compute the final selector.\n  constructor(spec, options) {\n    this.rules = []\n    let {finish} = options || {}\n\n    function splitSelector(selector) {\n      return /^@/.test(selector) ? [selector] : selector.split(/,\\s*/)\n    }\n\n    function render(selectors, spec, target, isKeyframes) {\n      let local = [], isAt = /^@(\\w+)\\b/.exec(selectors[0]), keyframes = isAt && isAt[1] == \"keyframes\"\n      if (isAt && spec == null) return target.push(selectors[0] + \";\")\n      for (let prop in spec) {\n        let value = spec[prop]\n        if (/&/.test(prop)) {\n          render(prop.split(/,\\s*/).map(part => selectors.map(sel => part.replace(/&/, sel))).reduce((a, b) => a.concat(b)),\n                 value, target)\n        } else if (value && typeof value == \"object\") {\n          if (!isAt) throw new RangeError(\"The value of a property (\" + prop + \") should be a primitive value.\")\n          render(splitSelector(prop), value, local, keyframes)\n        } else if (value != null) {\n          local.push(prop.replace(/_.*/, \"\").replace(/[A-Z]/g, l => \"-\" + l.toLowerCase()) + \": \" + value + \";\")\n        }\n      }\n      if (local.length || keyframes) {\n        target.push((finish && !isAt && !isKeyframes ? selectors.map(finish) : selectors).join(\", \") +\n                    \" {\" + local.join(\" \") + \"}\")\n      }\n    }\n\n    for (let prop in spec) render(splitSelector(prop), spec[prop], this.rules)\n  }\n\n  // :: () → string\n  // Returns a string containing the module's CSS rules.\n  getRules() { return this.rules.join(\"\\n\") }\n\n  // :: () → string\n  // Generate a new unique CSS class name.\n  static newName() {\n    let id = top[COUNT] || 1\n    top[COUNT] = id + 1\n    return C + id.toString(36)\n  }\n\n  // :: (union<Document, ShadowRoot>, union<[StyleModule], StyleModule>, ?{nonce: ?string})\n  //\n  // Mount the given set of modules in the given DOM root, which ensures\n  // that the CSS rules defined by the module are available in that\n  // context.\n  //\n  // Rules are only added to the document once per root.\n  //\n  // Rule order will follow the order of the modules, so that rules from\n  // modules later in the array take precedence of those from earlier\n  // modules. If you call this function multiple times for the same root\n  // in a way that changes the order of already mounted modules, the old\n  // order will be changed.\n  //\n  // If a Content Security Policy nonce is provided, it is added to\n  // the `<style>` tag generated by the library.\n  static mount(root, modules, options) {\n    let set = root[SET], nonce = options && options.nonce\n    if (!set) set = new StyleSet(root, nonce)\n    else if (nonce) set.setNonce(nonce)\n    set.mount(Array.isArray(modules) ? modules : [modules])\n  }\n}\n\nlet adoptedSet = new Map //<Document, StyleSet>\n\nclass StyleSet {\n  constructor(root, nonce) {\n    let doc = root.ownerDocument || root, win = doc.defaultView\n    if (!root.head && root.adoptedStyleSheets && win.CSSStyleSheet) {\n      let adopted = adoptedSet.get(doc)\n      if (adopted) {\n        root.adoptedStyleSheets = [adopted.sheet, ...root.adoptedStyleSheets]\n        return root[SET] = adopted\n      }\n      this.sheet = new win.CSSStyleSheet\n      root.adoptedStyleSheets = [this.sheet, ...root.adoptedStyleSheets]\n      adoptedSet.set(doc, this)\n    } else {\n      this.styleTag = doc.createElement(\"style\")\n      if (nonce) this.styleTag.setAttribute(\"nonce\", nonce)\n      let target = root.head || root\n      target.insertBefore(this.styleTag, target.firstChild)\n    }\n    this.modules = []\n    root[SET] = this\n  }\n\n  mount(modules) {\n    let sheet = this.sheet\n    let pos = 0 /* Current rule offset */, j = 0 /* Index into this.modules */\n    for (let i = 0; i < modules.length; i++) {\n      let mod = modules[i], index = this.modules.indexOf(mod)\n      if (index < j && index > -1) { // Ordering conflict\n        this.modules.splice(index, 1)\n        j--\n        index = -1\n      }\n      if (index == -1) {\n        this.modules.splice(j++, 0, mod)\n        if (sheet) for (let k = 0; k < mod.rules.length; k++)\n          sheet.insertRule(mod.rules[k], pos++)\n      } else {\n        while (j < index) pos += this.modules[j++].rules.length\n        pos += mod.rules.length\n        j++\n      }\n    }\n\n    if (!sheet) {\n      let text = \"\"\n      for (let i = 0; i < this.modules.length; i++)\n        text += this.modules[i].getRules() + \"\\n\"\n      this.styleTag.textContent = text\n    }\n  }\n\n  setNonce(nonce) {\n    if (this.styleTag && this.styleTag.getAttribute(\"nonce\") != nonce)\n      this.styleTag.setAttribute(\"nonce\", nonce)\n  }\n}\n\n// Style::Object<union<Style,string>>\n//\n// A style is an object that, in the simple case, maps CSS property\n// names to strings holding their values, as in `{color: \"red\",\n// fontWeight: \"bold\"}`. The property names can be given in\n// camel-case—the library will insert a dash before capital letters\n// when converting them to CSS.\n//\n// If you include an underscore in a property name, it and everything\n// after it will be removed from the output, which can be useful when\n// providing a property multiple times, for browser compatibility\n// reasons.\n//\n// A property in a style object can also be a sub-selector, which\n// extends the current context to add a pseudo-selector or a child\n// selector. Such a property should contain a `&` character, which\n// will be replaced by the current selector. For example `{\"&:before\":\n// {content: '\"hi\"'}}`. Sub-selectors and regular properties can\n// freely be mixed in a given object. Any property containing a `&` is\n// assumed to be a sub-selector.\n//\n// Finally, a property can specify an @-block to be wrapped around the\n// styles defined inside the object that's the property's value. For\n// example to create a media query you can do `{\"@media screen and\n// (min-width: 400px)\": {...}}`.\n\n\n//# sourceURL=webpack://_JUPYTERLAB.CORE_OUTPUT/../node_modules/style-mod/src/style-mod.js?");

/***/ }),

/***/ "../node_modules/w3c-keyname/index.js":
/*!********************************************!*\
  !*** ../node_modules/w3c-keyname/index.js ***!
  \********************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */   base: () => (/* binding */ base),\n/* harmony export */   keyName: () => (/* binding */ keyName),\n/* harmony export */   shift: () => (/* binding */ shift)\n/* harmony export */ });\nvar base = {\n  8: \"Backspace\",\n  9: \"Tab\",\n  10: \"Enter\",\n  12: \"NumLock\",\n  13: \"Enter\",\n  16: \"Shift\",\n  17: \"Control\",\n  18: \"Alt\",\n  20: \"CapsLock\",\n  27: \"Escape\",\n  32: \" \",\n  33: \"PageUp\",\n  34: \"PageDown\",\n  35: \"End\",\n  36: \"Home\",\n  37: \"ArrowLeft\",\n  38: \"ArrowUp\",\n  39: \"ArrowRight\",\n  40: \"ArrowDown\",\n  44: \"PrintScreen\",\n  45: \"Insert\",\n  46: \"Delete\",\n  59: \";\",\n  61: \"=\",\n  91: \"Meta\",\n  92: \"Meta\",\n  106: \"*\",\n  107: \"+\",\n  108: \",\",\n  109: \"-\",\n  110: \".\",\n  111: \"/\",\n  144: \"NumLock\",\n  145: \"ScrollLock\",\n  160: \"Shift\",\n  161: \"Shift\",\n  162: \"Control\",\n  163: \"Control\",\n  164: \"Alt\",\n  165: \"Alt\",\n  173: \"-\",\n  186: \";\",\n  187: \"=\",\n  188: \",\",\n  189: \"-\",\n  190: \".\",\n  191: \"/\",\n  192: \"`\",\n  219: \"[\",\n  220: \"\\\\\",\n  221: \"]\",\n  222: \"'\"\n}\n\nvar shift = {\n  48: \")\",\n  49: \"!\",\n  50: \"@\",\n  51: \"#\",\n  52: \"$\",\n  53: \"%\",\n  54: \"^\",\n  55: \"&\",\n  56: \"*\",\n  57: \"(\",\n  59: \":\",\n  61: \"+\",\n  173: \"_\",\n  186: \":\",\n  187: \"+\",\n  188: \"<\",\n  189: \"_\",\n  190: \">\",\n  191: \"?\",\n  192: \"~\",\n  219: \"{\",\n  220: \"|\",\n  221: \"}\",\n  222: \"\\\"\"\n}\n\nvar mac = typeof navigator != \"undefined\" && /Mac/.test(navigator.platform)\nvar ie = typeof navigator != \"undefined\" && /MSIE \\d|Trident\\/(?:[7-9]|\\d{2,})\\..*rv:(\\d+)/.exec(navigator.userAgent)\n\n// Fill in the digit keys\nfor (var i = 0; i < 10; i++) base[48 + i] = base[96 + i] = String(i)\n\n// The function keys\nfor (var i = 1; i <= 24; i++) base[i + 111] = \"F\" + i\n\n// And the alphabetic keys\nfor (var i = 65; i <= 90; i++) {\n  base[i] = String.fromCharCode(i + 32)\n  shift[i] = String.fromCharCode(i)\n}\n\n// For each code that doesn't have a shift-equivalent, copy the base name\nfor (var code in base) if (!shift.hasOwnProperty(code)) shift[code] = base[code]\n\nfunction keyName(event) {\n  // On macOS, keys held with Shift and Cmd don't reflect the effect of Shift in `.key`.\n  // On IE, shift effect is never included in `.key`.\n  var ignoreKey = mac && event.metaKey && event.shiftKey && !event.ctrlKey && !event.altKey ||\n      ie && event.shiftKey && event.key && event.key.length == 1 ||\n      event.key == \"Unidentified\"\n  var name = (!ignoreKey && event.key) ||\n    (event.shiftKey ? shift : base)[event.keyCode] ||\n    event.key || \"Unidentified\"\n  // Edge sometimes produces wrong names (Issue #3)\n  if (name == \"Esc\") name = \"Escape\"\n  if (name == \"Del\") name = \"Delete\"\n  // https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/8860571/\n  if (name == \"Left\") name = \"ArrowLeft\"\n  if (name == \"Up\") name = \"ArrowUp\"\n  if (name == \"Right\") name = \"ArrowRight\"\n  if (name == \"Down\") name = \"ArrowDown\"\n  return name\n}\n\n\n//# sourceURL=webpack://_JUPYTERLAB.CORE_OUTPUT/../node_modules/w3c-keyname/index.js?");

/***/ })

}]);