From 86d948e71a4f19f0ec24a9e5fa27f63238ca79c3 Mon Sep 17 00:00:00 2001 From: Josh Crawford Date: Wed, 14 Aug 2024 23:55:19 +1000 Subject: [PATCH] assets --- .../field/dist/assets/vizy-74cc0c71.js.map | 5 - .../assets/field/dist/assets/vizy-dae25c0e.js | 1152 ----------------- .../field/dist/assets/vizy-dae25c0e.js.gz | Bin 422758 -> 0 bytes .../field/dist/assets/vizy-dae25c0e.js.map | 5 - .../field/dist/assets/vizy-dae25c0e.js.map.gz | Bin 1692253 -> 0 bytes .../{vizy-74cc0c71.js => vizy-e0ccdefe.js} | 4 +- ...izy-74cc0c71.js.gz => vizy-e0ccdefe.js.gz} | Bin 423122 -> 423130 bytes .../field/dist/assets/vizy-e0ccdefe.js.map | 1 + ...0c71.js.map.gz => vizy-e0ccdefe.js.map.gz} | Bin 1692018 -> 1692041 bytes src/web/assets/field/dist/manifest.json | 6 +- 10 files changed, 4 insertions(+), 1169 deletions(-) delete mode 100644 src/web/assets/field/dist/assets/vizy-74cc0c71.js.map delete mode 100644 src/web/assets/field/dist/assets/vizy-dae25c0e.js delete mode 100644 src/web/assets/field/dist/assets/vizy-dae25c0e.js.gz delete mode 100644 src/web/assets/field/dist/assets/vizy-dae25c0e.js.map delete mode 100644 src/web/assets/field/dist/assets/vizy-dae25c0e.js.map.gz rename src/web/assets/field/dist/assets/{vizy-74cc0c71.js => vizy-e0ccdefe.js} (97%) rename src/web/assets/field/dist/assets/{vizy-74cc0c71.js.gz => vizy-e0ccdefe.js.gz} (75%) create mode 100644 src/web/assets/field/dist/assets/vizy-e0ccdefe.js.map rename src/web/assets/field/dist/assets/{vizy-74cc0c71.js.map.gz => vizy-e0ccdefe.js.map.gz} (58%) diff --git a/src/web/assets/field/dist/assets/vizy-74cc0c71.js.map b/src/web/assets/field/dist/assets/vizy-74cc0c71.js.map deleted file mode 100644 index 2636d8c..0000000 --- a/src/web/assets/field/dist/assets/vizy-74cc0c71.js.map +++ /dev/null @@ -1,5 +0,0 @@ -<<<<<<<< HEAD:src/web/assets/field/dist/assets/vizy-74cc0c71.js.map -{"version":3,"file":"vizy-74cc0c71.js","sources":["../../../../../../node_modules/@vue/shared/dist/shared.esm-bundler.js","../../../../../../node_modules/@vue/reactivity/dist/reactivity.esm-bundler.js","../../../../../../node_modules/@vue/runtime-core/dist/runtime-core.esm-bundler.js","../../../../../../node_modules/@vue/runtime-dom/dist/runtime-dom.esm-bundler.js","../../../../../../node_modules/@vue/compiler-core/dist/compiler-core.esm-bundler.js","../../../../../../node_modules/@vue/compiler-dom/dist/compiler-dom.esm-bundler.js","../../../../../../node_modules/vue/dist/vue.esm-bundler.js","../../../../../../node_modules/mitt/dist/mitt.es.js","../../../../../../node_modules/@floating-ui/core/dist/floating-ui.core.esm.js","../../../../../../node_modules/@floating-ui/dom/dist/floating-ui.dom.esm.js","../../../../../../node_modules/floating-vue/dist/floating-vue.es.js","../../../../../../node_modules/vue-final-modal/dist/VueFinalModal.esm.js","../../src/js/vendor/vue-unique-id/index.js","../../src/js/utils/object.js","../../../../../../node_modules/lodash-es/_freeGlobal.js","../../../../../../node_modules/lodash-es/_root.js","../../../../../../node_modules/lodash-es/_Symbol.js","../../../../../../node_modules/lodash-es/_getRawTag.js","../../../../../../node_modules/lodash-es/_objectToString.js","../../../../../../node_modules/lodash-es/_baseGetTag.js","../../../../../../node_modules/lodash-es/isObjectLike.js","../../../../../../node_modules/lodash-es/isSymbol.js","../../../../../../node_modules/lodash-es/_arrayMap.js","../../../../../../node_modules/lodash-es/isArray.js","../../../../../../node_modules/lodash-es/_baseToString.js","../../../../../../node_modules/lodash-es/_trimmedEndIndex.js","../../../../../../node_modules/lodash-es/_baseTrim.js","../../../../../../node_modules/lodash-es/isObject.js","../../../../../../node_modules/lodash-es/toNumber.js","../../../../../../node_modules/lodash-es/toFinite.js","../../../../../../node_modules/lodash-es/toInteger.js","../../../../../../node_modules/lodash-es/identity.js","../../../../../../node_modules/lodash-es/isFunction.js","../../../../../../node_modules/lodash-es/_coreJsData.js","../../../../../../node_modules/lodash-es/_isMasked.js","../../../../../../node_modules/lodash-es/_toSource.js","../../../../../../node_modules/lodash-es/_baseIsNative.js","../../../../../../node_modules/lodash-es/_getValue.js","../../../../../../node_modules/lodash-es/_getNative.js","../../../../../../node_modules/lodash-es/_WeakMap.js","../../../../../../node_modules/lodash-es/_baseCreate.js","../../../../../../node_modules/lodash-es/_apply.js","../../../../../../node_modules/lodash-es/_copyArray.js","../../../../../../node_modules/lodash-es/_shortOut.js","../../../../../../node_modules/lodash-es/constant.js","../../../../../../node_modules/lodash-es/_defineProperty.js","../../../../../../node_modules/lodash-es/_baseSetToString.js","../../../../../../node_modules/lodash-es/_setToString.js","../../../../../../node_modules/lodash-es/_baseFindIndex.js","../../../../../../node_modules/lodash-es/_isIndex.js","../../../../../../node_modules/lodash-es/_baseAssignValue.js","../../../../../../node_modules/lodash-es/eq.js","../../../../../../node_modules/lodash-es/_assignValue.js","../../../../../../node_modules/lodash-es/_copyObject.js","../../../../../../node_modules/lodash-es/_overRest.js","../../../../../../node_modules/lodash-es/_baseRest.js","../../../../../../node_modules/lodash-es/isLength.js","../../../../../../node_modules/lodash-es/isArrayLike.js","../../../../../../node_modules/lodash-es/_isIterateeCall.js","../../../../../../node_modules/lodash-es/_createAssigner.js","../../../../../../node_modules/lodash-es/_isPrototype.js","../../../../../../node_modules/lodash-es/_baseTimes.js","../../../../../../node_modules/lodash-es/_baseIsArguments.js","../../../../../../node_modules/lodash-es/isArguments.js","../../../../../../node_modules/lodash-es/stubFalse.js","../../../../../../node_modules/lodash-es/isBuffer.js","../../../../../../node_modules/lodash-es/_baseIsTypedArray.js","../../../../../../node_modules/lodash-es/_baseUnary.js","../../../../../../node_modules/lodash-es/_nodeUtil.js","../../../../../../node_modules/lodash-es/isTypedArray.js","../../../../../../node_modules/lodash-es/_arrayLikeKeys.js","../../../../../../node_modules/lodash-es/_overArg.js","../../../../../../node_modules/lodash-es/_nativeKeys.js","../../../../../../node_modules/lodash-es/_baseKeys.js","../../../../../../node_modules/lodash-es/keys.js","../../../../../../node_modules/lodash-es/_nativeKeysIn.js","../../../../../../node_modules/lodash-es/_baseKeysIn.js","../../../../../../node_modules/lodash-es/keysIn.js","../../../../../../node_modules/lodash-es/assignInWith.js","../../../../../../node_modules/lodash-es/_isKey.js","../../../../../../node_modules/lodash-es/_nativeCreate.js","../../../../../../node_modules/lodash-es/_hashClear.js","../../../../../../node_modules/lodash-es/_hashDelete.js","../../../../../../node_modules/lodash-es/_hashGet.js","../../../../../../node_modules/lodash-es/_hashHas.js","../../../../../../node_modules/lodash-es/_hashSet.js","../../../../../../node_modules/lodash-es/_Hash.js","../../../../../../node_modules/lodash-es/_listCacheClear.js","../../../../../../node_modules/lodash-es/_assocIndexOf.js","../../../../../../node_modules/lodash-es/_listCacheDelete.js","../../../../../../node_modules/lodash-es/_listCacheGet.js","../../../../../../node_modules/lodash-es/_listCacheHas.js","../../../../../../node_modules/lodash-es/_listCacheSet.js","../../../../../../node_modules/lodash-es/_ListCache.js","../../../../../../node_modules/lodash-es/_Map.js","../../../../../../node_modules/lodash-es/_mapCacheClear.js","../../../../../../node_modules/lodash-es/_isKeyable.js","../../../../../../node_modules/lodash-es/_getMapData.js","../../../../../../node_modules/lodash-es/_mapCacheDelete.js","../../../../../../node_modules/lodash-es/_mapCacheGet.js","../../../../../../node_modules/lodash-es/_mapCacheHas.js","../../../../../../node_modules/lodash-es/_mapCacheSet.js","../../../../../../node_modules/lodash-es/_MapCache.js","../../../../../../node_modules/lodash-es/memoize.js","../../../../../../node_modules/lodash-es/_memoizeCapped.js","../../../../../../node_modules/lodash-es/_stringToPath.js","../../../../../../node_modules/lodash-es/toString.js","../../../../../../node_modules/lodash-es/_castPath.js","../../../../../../node_modules/lodash-es/_toKey.js","../../../../../../node_modules/lodash-es/_baseGet.js","../../../../../../node_modules/lodash-es/get.js","../../../../../../node_modules/lodash-es/_arrayPush.js","../../../../../../node_modules/lodash-es/_getPrototype.js","../../../../../../node_modules/lodash-es/isPlainObject.js","../../../../../../node_modules/lodash-es/isError.js","../../../../../../node_modules/lodash-es/attempt.js","../../../../../../node_modules/lodash-es/_hasUnicode.js","../../../../../../node_modules/lodash-es/_arrayReduce.js","../../../../../../node_modules/lodash-es/_basePropertyOf.js","../../../../../../node_modules/lodash-es/_deburrLetter.js","../../../../../../node_modules/lodash-es/deburr.js","../../../../../../node_modules/lodash-es/_asciiWords.js","../../../../../../node_modules/lodash-es/_hasUnicodeWord.js","../../../../../../node_modules/lodash-es/_unicodeWords.js","../../../../../../node_modules/lodash-es/words.js","../../../../../../node_modules/lodash-es/_createCompounder.js","../../../../../../node_modules/lodash-es/_stackClear.js","../../../../../../node_modules/lodash-es/_stackDelete.js","../../../../../../node_modules/lodash-es/_stackGet.js","../../../../../../node_modules/lodash-es/_stackHas.js","../../../../../../node_modules/lodash-es/_stackSet.js","../../../../../../node_modules/lodash-es/_Stack.js","../../../../../../node_modules/lodash-es/_cloneBuffer.js","../../../../../../node_modules/lodash-es/_arrayFilter.js","../../../../../../node_modules/lodash-es/stubArray.js","../../../../../../node_modules/lodash-es/_getSymbols.js","../../../../../../node_modules/lodash-es/_baseGetAllKeys.js","../../../../../../node_modules/lodash-es/_getAllKeys.js","../../../../../../node_modules/lodash-es/_DataView.js","../../../../../../node_modules/lodash-es/_Promise.js","../../../../../../node_modules/lodash-es/_Set.js","../../../../../../node_modules/lodash-es/_getTag.js","../../../../../../node_modules/lodash-es/_Uint8Array.js","../../../../../../node_modules/lodash-es/_cloneArrayBuffer.js","../../../../../../node_modules/lodash-es/_cloneTypedArray.js","../../../../../../node_modules/lodash-es/_initCloneObject.js","../../../../../../node_modules/lodash-es/_setCacheAdd.js","../../../../../../node_modules/lodash-es/_setCacheHas.js","../../../../../../node_modules/lodash-es/_SetCache.js","../../../../../../node_modules/lodash-es/_arraySome.js","../../../../../../node_modules/lodash-es/_cacheHas.js","../../../../../../node_modules/lodash-es/_equalArrays.js","../../../../../../node_modules/lodash-es/_mapToArray.js","../../../../../../node_modules/lodash-es/_setToArray.js","../../../../../../node_modules/lodash-es/_equalByTag.js","../../../../../../node_modules/lodash-es/_equalObjects.js","../../../../../../node_modules/lodash-es/_baseIsEqualDeep.js","../../../../../../node_modules/lodash-es/_baseIsEqual.js","../../../../../../node_modules/lodash-es/_baseIsMatch.js","../../../../../../node_modules/lodash-es/_isStrictComparable.js","../../../../../../node_modules/lodash-es/_getMatchData.js","../../../../../../node_modules/lodash-es/_matchesStrictComparable.js","../../../../../../node_modules/lodash-es/_baseMatches.js","../../../../../../node_modules/lodash-es/_baseHasIn.js","../../../../../../node_modules/lodash-es/_hasPath.js","../../../../../../node_modules/lodash-es/hasIn.js","../../../../../../node_modules/lodash-es/_baseMatchesProperty.js","../../../../../../node_modules/lodash-es/_baseProperty.js","../../../../../../node_modules/lodash-es/_basePropertyDeep.js","../../../../../../node_modules/lodash-es/property.js","../../../../../../node_modules/lodash-es/_baseIteratee.js","../../../../../../node_modules/lodash-es/_createBaseFor.js","../../../../../../node_modules/lodash-es/_baseFor.js","../../../../../../node_modules/lodash-es/now.js","../../../../../../node_modules/lodash-es/debounce.js","../../../../../../node_modules/lodash-es/_assignMergeValue.js","../../../../../../node_modules/lodash-es/isArrayLikeObject.js","../../../../../../node_modules/lodash-es/_safeGet.js","../../../../../../node_modules/lodash-es/toPlainObject.js","../../../../../../node_modules/lodash-es/_baseMergeDeep.js","../../../../../../node_modules/lodash-es/_baseMerge.js","../../../../../../node_modules/lodash-es/_escapeHtmlChar.js","../../../../../../node_modules/lodash-es/escape.js","../../../../../../node_modules/lodash-es/_createFind.js","../../../../../../node_modules/lodash-es/findIndex.js","../../../../../../node_modules/lodash-es/find.js","../../../../../../node_modules/lodash-es/isString.js","../../../../../../node_modules/lodash-es/_baseValues.js","../../../../../../node_modules/lodash-es/isEmpty.js","../../../../../../node_modules/lodash-es/kebabCase.js","../../../../../../node_modules/lodash-es/merge.js","../../../../../../node_modules/lodash-es/_asciiSize.js","../../../../../../node_modules/lodash-es/_unicodeSize.js","../../../../../../node_modules/lodash-es/_stringSize.js","../../../../../../node_modules/lodash-es/size.js","../../../../../../node_modules/lodash-es/_customDefaultsAssignIn.js","../../../../../../node_modules/lodash-es/_escapeStringChar.js","../../../../../../node_modules/lodash-es/_reInterpolate.js","../../../../../../node_modules/lodash-es/_reEscape.js","../../../../../../node_modules/lodash-es/_reEvaluate.js","../../../../../../node_modules/lodash-es/templateSettings.js","../../../../../../node_modules/lodash-es/template.js","../../src/js/utils/translations.js","../../src/js/config.js","../../../../../../node_modules/orderedmap/dist/index.js","../../../../../../node_modules/prosemirror-model/dist/index.js","../../../../../../node_modules/prosemirror-transform/dist/index.js","../../../../../../node_modules/prosemirror-state/dist/index.js","../../../../../../node_modules/prosemirror-view/dist/index.js","../../../../../../node_modules/w3c-keyname/index.es.js","../../../../../../node_modules/prosemirror-keymap/dist/index.js","../../../../../../node_modules/prosemirror-commands/dist/index.js","../../../../../../node_modules/prosemirror-schema-list/dist/index.js","../../../../../../node_modules/@tiptap/core/dist/index.js","../../src/js/config/Buttons.js","../../../../../../node_modules/@tiptap/extension-bold/dist/index.js","../../../../../../node_modules/@tiptap/extension-code/dist/index.js","../../../../../../node_modules/@tiptap/extension-highlight/dist/index.js","../../../../../../node_modules/@tiptap/extension-italic/dist/index.js","../../../../../../node_modules/@tiptap/extension-strike/dist/index.js","../../../../../../node_modules/@tiptap/extension-subscript/dist/index.js","../../../../../../node_modules/@tiptap/extension-superscript/dist/index.js","../../../../../../node_modules/@tiptap/extension-underline/dist/index.js","../../../../../../node_modules/@tiptap/extension-blockquote/dist/index.js","../../../../../../node_modules/@tiptap/extension-bullet-list/dist/index.js","../../../../../../node_modules/@tiptap/extension-code-block/dist/index.js","../../../../../../node_modules/@tiptap/extension-document/dist/index.js","../../../../../../node_modules/@tiptap/extension-hard-break/dist/index.js","../../../../../../node_modules/@tiptap/extension-heading/dist/index.js","../../../../../../node_modules/@tiptap/extension-horizontal-rule/dist/index.js","../../../../../../node_modules/@tiptap/extension-list-item/dist/index.js","../../../../../../node_modules/@tiptap/extension-ordered-list/dist/index.js","../../../../../../node_modules/@tiptap/extension-paragraph/dist/index.js","../../../../../../node_modules/prosemirror-tables/dist/index.js","../../../../../../node_modules/@tiptap/extension-table/dist/index.js","../../../../../../node_modules/@tiptap/extension-table-cell/dist/index.js","../../../../../../node_modules/@tiptap/extension-table-header/dist/index.js","../../../../../../node_modules/@tiptap/extension-table-row/dist/index.js","../../../../../../node_modules/@tiptap/extension-text/dist/index.js","../../../../../../node_modules/prosemirror-dropcursor/dist/index.js","../../../../../../node_modules/@tiptap/extension-dropcursor/dist/index.js","../../../../../../node_modules/@tiptap/extension-focus/dist/index.js","../../../../../../node_modules/prosemirror-gapcursor/dist/index.js","../../../../../../node_modules/@tiptap/extension-gapcursor/dist/index.js","../../../../../../node_modules/rope-sequence/dist/index.es.js","../../../../../../node_modules/prosemirror-history/dist/index.js","../../../../../../node_modules/@tiptap/extension-history/dist/index.js","../../../../../../node_modules/@tiptap/extension-text-align/dist/index.js","../../../../../../node_modules/linkifyjs/dist/linkify.es.js","../../../../../../node_modules/@tiptap/extension-link/dist/index.js","../../src/js/components/input/link/Link.js","../../../../../../node_modules/@tiptap/extension-image/dist/index.js","../../src/js/components/input/image/Image.js","../../../../../../node_modules/@popperjs/core/lib/enums.js","../../../../../../node_modules/@popperjs/core/lib/dom-utils/getNodeName.js","../../../../../../node_modules/@popperjs/core/lib/dom-utils/getWindow.js","../../../../../../node_modules/@popperjs/core/lib/dom-utils/instanceOf.js","../../../../../../node_modules/@popperjs/core/lib/modifiers/applyStyles.js","../../../../../../node_modules/@popperjs/core/lib/utils/getBasePlacement.js","../../../../../../node_modules/@popperjs/core/lib/utils/math.js","../../../../../../node_modules/@popperjs/core/lib/utils/userAgent.js","../../../../../../node_modules/@popperjs/core/lib/dom-utils/isLayoutViewport.js","../../../../../../node_modules/@popperjs/core/lib/dom-utils/getBoundingClientRect.js","../../../../../../node_modules/@popperjs/core/lib/dom-utils/getLayoutRect.js","../../../../../../node_modules/@popperjs/core/lib/dom-utils/contains.js","../../../../../../node_modules/@popperjs/core/lib/dom-utils/getComputedStyle.js","../../../../../../node_modules/@popperjs/core/lib/dom-utils/isTableElement.js","../../../../../../node_modules/@popperjs/core/lib/dom-utils/getDocumentElement.js","../../../../../../node_modules/@popperjs/core/lib/dom-utils/getParentNode.js","../../../../../../node_modules/@popperjs/core/lib/dom-utils/getOffsetParent.js","../../../../../../node_modules/@popperjs/core/lib/utils/getMainAxisFromPlacement.js","../../../../../../node_modules/@popperjs/core/lib/utils/within.js","../../../../../../node_modules/@popperjs/core/lib/utils/getFreshSideObject.js","../../../../../../node_modules/@popperjs/core/lib/utils/mergePaddingObject.js","../../../../../../node_modules/@popperjs/core/lib/utils/expandToHashMap.js","../../../../../../node_modules/@popperjs/core/lib/modifiers/arrow.js","../../../../../../node_modules/@popperjs/core/lib/utils/getVariation.js","../../../../../../node_modules/@popperjs/core/lib/modifiers/computeStyles.js","../../../../../../node_modules/@popperjs/core/lib/modifiers/eventListeners.js","../../../../../../node_modules/@popperjs/core/lib/utils/getOppositePlacement.js","../../../../../../node_modules/@popperjs/core/lib/utils/getOppositeVariationPlacement.js","../../../../../../node_modules/@popperjs/core/lib/dom-utils/getWindowScroll.js","../../../../../../node_modules/@popperjs/core/lib/dom-utils/getWindowScrollBarX.js","../../../../../../node_modules/@popperjs/core/lib/dom-utils/getViewportRect.js","../../../../../../node_modules/@popperjs/core/lib/dom-utils/getDocumentRect.js","../../../../../../node_modules/@popperjs/core/lib/dom-utils/isScrollParent.js","../../../../../../node_modules/@popperjs/core/lib/dom-utils/getScrollParent.js","../../../../../../node_modules/@popperjs/core/lib/dom-utils/listScrollParents.js","../../../../../../node_modules/@popperjs/core/lib/utils/rectToClientRect.js","../../../../../../node_modules/@popperjs/core/lib/dom-utils/getClippingRect.js","../../../../../../node_modules/@popperjs/core/lib/utils/computeOffsets.js","../../../../../../node_modules/@popperjs/core/lib/utils/detectOverflow.js","../../../../../../node_modules/@popperjs/core/lib/utils/computeAutoPlacement.js","../../../../../../node_modules/@popperjs/core/lib/modifiers/flip.js","../../../../../../node_modules/@popperjs/core/lib/modifiers/hide.js","../../../../../../node_modules/@popperjs/core/lib/modifiers/offset.js","../../../../../../node_modules/@popperjs/core/lib/modifiers/popperOffsets.js","../../../../../../node_modules/@popperjs/core/lib/utils/getAltAxis.js","../../../../../../node_modules/@popperjs/core/lib/modifiers/preventOverflow.js","../../../../../../node_modules/@popperjs/core/lib/dom-utils/getHTMLElementScroll.js","../../../../../../node_modules/@popperjs/core/lib/dom-utils/getNodeScroll.js","../../../../../../node_modules/@popperjs/core/lib/dom-utils/getCompositeRect.js","../../../../../../node_modules/@popperjs/core/lib/utils/orderModifiers.js","../../../../../../node_modules/@popperjs/core/lib/utils/debounce.js","../../../../../../node_modules/@popperjs/core/lib/utils/mergeByName.js","../../../../../../node_modules/@popperjs/core/lib/createPopper.js","../../../../../../node_modules/@popperjs/core/lib/popper.js","../../../../../../node_modules/tippy.js/dist/tippy.esm.js","../../../../../../node_modules/@tiptap/vue-3/dist/index.js","../../src/js/components/input/iframe/IframeView.vue","../../src/js/components/input/iframe/Iframe.js","../../../../../../node_modules/@extractus/oembed-extractor/src/utils/linker.js","../../../../../../node_modules/@extractus/oembed-extractor/src/deno/cross-fetch.js","../../../../../../node_modules/@extractus/oembed-extractor/src/utils/retrieve.js","../../../../../../node_modules/@extractus/oembed-extractor/src/utils/fetchEmbed.js","../../../../../../node_modules/@extractus/oembed-extractor/src/utils/providers.latest.js","../../../../../../node_modules/@extractus/oembed-extractor/src/utils/provider.js","../../../../../../node_modules/@extractus/oembed-extractor/src/main.js","../../src/js/utils/forms.js","../../src/js/components/input/media-embed/MediaEmbedView.vue","../../src/js/components/input/media-embed/MediaEmbed.js","../../src/js/config/Extensions.js","../../src/js/config/Commands.js","../../src/js/VizyConfig.js","../../../../../../node_modules/@tiptap/extension-text-style/dist/index.js","../../../../../../node_modules/@ivanv/vue-collapse-transition/src/CollapseTransition.vue","../../src/js/utils/bool.js","../../src/js/components/settings/LightswitchField.vue","../../src/js/components/input/VizyBlockFields.vue","../../src/js/utils/htmlize.js","../../src/js/components/input/VizyBlock.vue","../../src/js/components/input/VizyBlock.js","../../../../../../node_modules/@tiptap/suggestion/dist/index.js","../../src/js/components/input/commands/Commands.js","../../src/js/utils/string.js","../../../../../../node_modules/@fortawesome/fontawesome-svg-core/index.mjs","../../../../../../node_modules/@fortawesome/vue-fontawesome/index.es.js","../../../../../../node_modules/@fortawesome/free-solid-svg-icons/index.mjs","../../src/js/components/input/SvgIcon.vue","../../src/js/components/input/commands/CommandsList.vue","../../src/js/components/input/commands/Suggestion.js","../../src/js/components/input/GlobalAttributes.js","../../src/js/components/input/MenuBarItem.vue","../../src/js/utils/tiptap/marks.js","../../src/js/components/input/MenuBarModal.vue","../../src/js/components/input/link/LinkMenuModal.vue","../../src/js/components/input/link/LinkMenuBubble.vue","../../src/js/components/input/link/LinkMenuBarItem.vue","../../src/js/components/input/image/ImageMenuModal.vue","../../src/js/utils/tiptap/nodes.js","../../src/js/utils/tippy/followCursor.js","../../src/js/components/input/image/ImageMenuBubble.vue","../../src/js/components/input/image/ImageMenuBarItem.vue","../../src/js/components/input/iframe/IframeMenuModal.vue","../../src/js/components/input/iframe/IframeMenuBubble.vue","../../src/js/components/input/iframe/IframeMenuBarItem.vue","../../src/js/components/input/media-embed/MediaEmbedMenuModal.vue","../../src/js/components/input/media-embed/MediaEmbedMenuBubble.vue","../../src/js/components/input/media-embed/MediaEmbedMenuBarItem.vue","../../src/js/components/input/MenuBar.vue","../../src/js/components/input/FloatingMenu.js","../../src/js/components/input/FloatingMenu.vue","../../src/js/components/input/BlockPicker.vue","../../../../../../node_modules/codemirror/lib/codemirror.js","../../../../../../node_modules/codemirror/addon/merge/merge.js","../../../../../../node_modules/diff-match-patch/index.js","../../../../../../node_modules/codemirror/addon/mode/simple.js","../../../../../../node_modules/codemirror-editor-vue3/dist/codemirror-editor-vue3.js","../../../../../../node_modules/js-beautify/js/src/core/output.js","../../../../../../node_modules/js-beautify/js/src/core/token.js","../../../../../../node_modules/js-beautify/js/src/javascript/acorn.js","../../../../../../node_modules/js-beautify/js/src/core/options.js","../../../../../../node_modules/js-beautify/js/src/javascript/options.js","../../../../../../node_modules/js-beautify/js/src/core/inputscanner.js","../../../../../../node_modules/js-beautify/js/src/core/tokenstream.js","../../../../../../node_modules/js-beautify/js/src/core/pattern.js","../../../../../../node_modules/js-beautify/js/src/core/whitespacepattern.js","../../../../../../node_modules/js-beautify/js/src/core/tokenizer.js","../../../../../../node_modules/js-beautify/js/src/core/directives.js","../../../../../../node_modules/js-beautify/js/src/core/templatablepattern.js","../../../../../../node_modules/js-beautify/js/src/javascript/tokenizer.js","../../../../../../node_modules/js-beautify/js/src/javascript/beautifier.js","../../../../../../node_modules/js-beautify/js/src/javascript/index.js","../../../../../../node_modules/js-beautify/js/src/css/options.js","../../../../../../node_modules/js-beautify/js/src/css/beautifier.js","../../../../../../node_modules/js-beautify/js/src/css/index.js","../../../../../../node_modules/js-beautify/js/src/html/options.js","../../../../../../node_modules/js-beautify/js/src/html/tokenizer.js","../../../../../../node_modules/js-beautify/js/src/html/beautifier.js","../../../../../../node_modules/js-beautify/js/src/html/index.js","../../../../../../node_modules/js-beautify/js/src/index.js","../../../../../../node_modules/js-beautify/js/index.js","../../../../../../node_modules/codemirror/addon/mode/overlay.js","../../../../../../node_modules/codemirror/mode/xml/xml.js","../../../../../../node_modules/codemirror/mode/javascript/javascript.js","../../../../../../node_modules/codemirror/mode/coffeescript/coffeescript.js","../../../../../../node_modules/codemirror/mode/css/css.js","../../../../../../node_modules/codemirror/mode/sass/sass.js","../../../../../../node_modules/codemirror/mode/stylus/stylus.js","../../../../../../node_modules/codemirror/mode/htmlmixed/htmlmixed.js","../../../../../../node_modules/codemirror/mode/pug/pug.js","../../../../../../node_modules/codemirror/addon/mode/multiplex.js","../../../../../../node_modules/codemirror/mode/handlebars/handlebars.js","../../../../../../node_modules/codemirror/mode/vue/vue.js","../../src/js/components/input/CodeEditor.vue","../../src/js/components/input/VizyUserTemplate.vue","../../src/js/components/VizyInput.vue","../../src/js/vendor/vue-drag-drop/transferDataStore.js","../../src/js/vendor/vue-drag-drop/constants.js","../../src/js/vendor/vue-drag-drop/Drag.vue","../../src/js/vendor/vue-drag-drop/Drop.vue","../../src/js/components/settings/VizyIconPicker.vue","../../src/js/components/settings/FieldLayoutDesigner.vue","../../src/js/vendor/vue-autosuggest/parts/DefaultSection.js","../../src/js/vendor/vue-autosuggest/utils.js","../../src/js/vendor/vue-autosuggest/Autosuggest.vue","../../src/js/components/settings/AutoSuggest.vue","../../src/js/components/settings/HandleInput.vue","../../src/js/utils/browser.js","../../src/js/components/VizySettings.vue","../../src/js/vizy.js"],"sourcesContent":["/**\n* @vue/shared v3.4.15\n* (c) 2018-present Yuxi (Evan) You and Vue contributors\n* @license MIT\n**/\nfunction makeMap(str, expectsLowerCase) {\n const set = new Set(str.split(\",\"));\n return expectsLowerCase ? (val) => set.has(val.toLowerCase()) : (val) => set.has(val);\n}\n\nconst EMPTY_OBJ = !!(process.env.NODE_ENV !== \"production\") ? Object.freeze({}) : {};\nconst EMPTY_ARR = !!(process.env.NODE_ENV !== \"production\") ? Object.freeze([]) : [];\nconst NOOP = () => {\n};\nconst NO = () => false;\nconst isOn = (key) => key.charCodeAt(0) === 111 && key.charCodeAt(1) === 110 && // uppercase letter\n(key.charCodeAt(2) > 122 || key.charCodeAt(2) < 97);\nconst isModelListener = (key) => key.startsWith(\"onUpdate:\");\nconst extend = Object.assign;\nconst remove = (arr, el) => {\n const i = arr.indexOf(el);\n if (i > -1) {\n arr.splice(i, 1);\n }\n};\nconst hasOwnProperty = Object.prototype.hasOwnProperty;\nconst hasOwn = (val, key) => hasOwnProperty.call(val, key);\nconst isArray = Array.isArray;\nconst isMap = (val) => toTypeString(val) === \"[object Map]\";\nconst isSet = (val) => toTypeString(val) === \"[object Set]\";\nconst isDate = (val) => toTypeString(val) === \"[object Date]\";\nconst isRegExp = (val) => toTypeString(val) === \"[object RegExp]\";\nconst isFunction = (val) => typeof val === \"function\";\nconst isString = (val) => typeof val === \"string\";\nconst isSymbol = (val) => typeof val === \"symbol\";\nconst isObject = (val) => val !== null && typeof val === \"object\";\nconst isPromise = (val) => {\n return (isObject(val) || isFunction(val)) && isFunction(val.then) && isFunction(val.catch);\n};\nconst objectToString = Object.prototype.toString;\nconst toTypeString = (value) => objectToString.call(value);\nconst toRawType = (value) => {\n return toTypeString(value).slice(8, -1);\n};\nconst isPlainObject = (val) => toTypeString(val) === \"[object Object]\";\nconst isIntegerKey = (key) => isString(key) && key !== \"NaN\" && key[0] !== \"-\" && \"\" + parseInt(key, 10) === key;\nconst isReservedProp = /* @__PURE__ */ makeMap(\n // the leading comma is intentional so empty string \"\" is also included\n \",key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted\"\n);\nconst isBuiltInDirective = /* @__PURE__ */ makeMap(\n \"bind,cloak,else-if,else,for,html,if,model,on,once,pre,show,slot,text,memo\"\n);\nconst cacheStringFunction = (fn) => {\n const cache = /* @__PURE__ */ Object.create(null);\n return (str) => {\n const hit = cache[str];\n return hit || (cache[str] = fn(str));\n };\n};\nconst camelizeRE = /-(\\w)/g;\nconst camelize = cacheStringFunction((str) => {\n return str.replace(camelizeRE, (_, c) => c ? c.toUpperCase() : \"\");\n});\nconst hyphenateRE = /\\B([A-Z])/g;\nconst hyphenate = cacheStringFunction(\n (str) => str.replace(hyphenateRE, \"-$1\").toLowerCase()\n);\nconst capitalize = cacheStringFunction((str) => {\n return str.charAt(0).toUpperCase() + str.slice(1);\n});\nconst toHandlerKey = cacheStringFunction((str) => {\n const s = str ? `on${capitalize(str)}` : ``;\n return s;\n});\nconst hasChanged = (value, oldValue) => !Object.is(value, oldValue);\nconst invokeArrayFns = (fns, arg) => {\n for (let i = 0; i < fns.length; i++) {\n fns[i](arg);\n }\n};\nconst def = (obj, key, value) => {\n Object.defineProperty(obj, key, {\n configurable: true,\n enumerable: false,\n value\n });\n};\nconst looseToNumber = (val) => {\n const n = parseFloat(val);\n return isNaN(n) ? val : n;\n};\nconst toNumber = (val) => {\n const n = isString(val) ? Number(val) : NaN;\n return isNaN(n) ? val : n;\n};\nlet _globalThis;\nconst getGlobalThis = () => {\n return _globalThis || (_globalThis = typeof globalThis !== \"undefined\" ? globalThis : typeof self !== \"undefined\" ? self : typeof window !== \"undefined\" ? window : typeof global !== \"undefined\" ? global : {});\n};\nconst identRE = /^[_$a-zA-Z\\xA0-\\uFFFF][_$a-zA-Z0-9\\xA0-\\uFFFF]*$/;\nfunction genPropsAccessExp(name) {\n return identRE.test(name) ? `__props.${name}` : `__props[${JSON.stringify(name)}]`;\n}\n\nconst PatchFlags = {\n \"TEXT\": 1,\n \"1\": \"TEXT\",\n \"CLASS\": 2,\n \"2\": \"CLASS\",\n \"STYLE\": 4,\n \"4\": \"STYLE\",\n \"PROPS\": 8,\n \"8\": \"PROPS\",\n \"FULL_PROPS\": 16,\n \"16\": \"FULL_PROPS\",\n \"NEED_HYDRATION\": 32,\n \"32\": \"NEED_HYDRATION\",\n \"STABLE_FRAGMENT\": 64,\n \"64\": \"STABLE_FRAGMENT\",\n \"KEYED_FRAGMENT\": 128,\n \"128\": \"KEYED_FRAGMENT\",\n \"UNKEYED_FRAGMENT\": 256,\n \"256\": \"UNKEYED_FRAGMENT\",\n \"NEED_PATCH\": 512,\n \"512\": \"NEED_PATCH\",\n \"DYNAMIC_SLOTS\": 1024,\n \"1024\": \"DYNAMIC_SLOTS\",\n \"DEV_ROOT_FRAGMENT\": 2048,\n \"2048\": \"DEV_ROOT_FRAGMENT\",\n \"HOISTED\": -1,\n \"-1\": \"HOISTED\",\n \"BAIL\": -2,\n \"-2\": \"BAIL\"\n};\nconst PatchFlagNames = {\n [1]: `TEXT`,\n [2]: `CLASS`,\n [4]: `STYLE`,\n [8]: `PROPS`,\n [16]: `FULL_PROPS`,\n [32]: `NEED_HYDRATION`,\n [64]: `STABLE_FRAGMENT`,\n [128]: `KEYED_FRAGMENT`,\n [256]: `UNKEYED_FRAGMENT`,\n [512]: `NEED_PATCH`,\n [1024]: `DYNAMIC_SLOTS`,\n [2048]: `DEV_ROOT_FRAGMENT`,\n [-1]: `HOISTED`,\n [-2]: `BAIL`\n};\n\nconst ShapeFlags = {\n \"ELEMENT\": 1,\n \"1\": \"ELEMENT\",\n \"FUNCTIONAL_COMPONENT\": 2,\n \"2\": \"FUNCTIONAL_COMPONENT\",\n \"STATEFUL_COMPONENT\": 4,\n \"4\": \"STATEFUL_COMPONENT\",\n \"TEXT_CHILDREN\": 8,\n \"8\": \"TEXT_CHILDREN\",\n \"ARRAY_CHILDREN\": 16,\n \"16\": \"ARRAY_CHILDREN\",\n \"SLOTS_CHILDREN\": 32,\n \"32\": \"SLOTS_CHILDREN\",\n \"TELEPORT\": 64,\n \"64\": \"TELEPORT\",\n \"SUSPENSE\": 128,\n \"128\": \"SUSPENSE\",\n \"COMPONENT_SHOULD_KEEP_ALIVE\": 256,\n \"256\": \"COMPONENT_SHOULD_KEEP_ALIVE\",\n \"COMPONENT_KEPT_ALIVE\": 512,\n \"512\": \"COMPONENT_KEPT_ALIVE\",\n \"COMPONENT\": 6,\n \"6\": \"COMPONENT\"\n};\n\nconst SlotFlags = {\n \"STABLE\": 1,\n \"1\": \"STABLE\",\n \"DYNAMIC\": 2,\n \"2\": \"DYNAMIC\",\n \"FORWARDED\": 3,\n \"3\": \"FORWARDED\"\n};\nconst slotFlagsText = {\n [1]: \"STABLE\",\n [2]: \"DYNAMIC\",\n [3]: \"FORWARDED\"\n};\n\nconst GLOBALS_ALLOWED = \"Infinity,undefined,NaN,isFinite,isNaN,parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,BigInt,console,Error\";\nconst isGloballyAllowed = /* @__PURE__ */ makeMap(GLOBALS_ALLOWED);\nconst isGloballyWhitelisted = isGloballyAllowed;\n\nconst range = 2;\nfunction generateCodeFrame(source, start = 0, end = source.length) {\n let lines = source.split(/(\\r?\\n)/);\n const newlineSequences = lines.filter((_, idx) => idx % 2 === 1);\n lines = lines.filter((_, idx) => idx % 2 === 0);\n let count = 0;\n const res = [];\n for (let i = 0; i < lines.length; i++) {\n count += lines[i].length + (newlineSequences[i] && newlineSequences[i].length || 0);\n if (count >= start) {\n for (let j = i - range; j <= i + range || end > count; j++) {\n if (j < 0 || j >= lines.length)\n continue;\n const line = j + 1;\n res.push(\n `${line}${\" \".repeat(Math.max(3 - String(line).length, 0))}| ${lines[j]}`\n );\n const lineLength = lines[j].length;\n const newLineSeqLength = newlineSequences[j] && newlineSequences[j].length || 0;\n if (j === i) {\n const pad = start - (count - (lineLength + newLineSeqLength));\n const length = Math.max(\n 1,\n end > count ? lineLength - pad : end - start\n );\n res.push(` | ` + \" \".repeat(pad) + \"^\".repeat(length));\n } else if (j > i) {\n if (end > count) {\n const length = Math.max(Math.min(end - count, lineLength), 1);\n res.push(` | ` + \"^\".repeat(length));\n }\n count += lineLength + newLineSeqLength;\n }\n }\n break;\n }\n }\n return res.join(\"\\n\");\n}\n\nfunction normalizeStyle(value) {\n if (isArray(value)) {\n const res = {};\n for (let i = 0; i < value.length; i++) {\n const item = value[i];\n const normalized = isString(item) ? parseStringStyle(item) : normalizeStyle(item);\n if (normalized) {\n for (const key in normalized) {\n res[key] = normalized[key];\n }\n }\n }\n return res;\n } else if (isString(value) || isObject(value)) {\n return value;\n }\n}\nconst listDelimiterRE = /;(?![^(]*\\))/g;\nconst propertyDelimiterRE = /:([^]+)/;\nconst styleCommentRE = /\\/\\*[^]*?\\*\\//g;\nfunction parseStringStyle(cssText) {\n const ret = {};\n cssText.replace(styleCommentRE, \"\").split(listDelimiterRE).forEach((item) => {\n if (item) {\n const tmp = item.split(propertyDelimiterRE);\n tmp.length > 1 && (ret[tmp[0].trim()] = tmp[1].trim());\n }\n });\n return ret;\n}\nfunction stringifyStyle(styles) {\n let ret = \"\";\n if (!styles || isString(styles)) {\n return ret;\n }\n for (const key in styles) {\n const value = styles[key];\n const normalizedKey = key.startsWith(`--`) ? key : hyphenate(key);\n if (isString(value) || typeof value === \"number\") {\n ret += `${normalizedKey}:${value};`;\n }\n }\n return ret;\n}\nfunction normalizeClass(value) {\n let res = \"\";\n if (isString(value)) {\n res = value;\n } else if (isArray(value)) {\n for (let i = 0; i < value.length; i++) {\n const normalized = normalizeClass(value[i]);\n if (normalized) {\n res += normalized + \" \";\n }\n }\n } else if (isObject(value)) {\n for (const name in value) {\n if (value[name]) {\n res += name + \" \";\n }\n }\n }\n return res.trim();\n}\nfunction normalizeProps(props) {\n if (!props)\n return null;\n let { class: klass, style } = props;\n if (klass && !isString(klass)) {\n props.class = normalizeClass(klass);\n }\n if (style) {\n props.style = normalizeStyle(style);\n }\n return props;\n}\n\nconst HTML_TAGS = \"html,body,base,head,link,meta,style,title,address,article,aside,footer,header,hgroup,h1,h2,h3,h4,h5,h6,nav,section,div,dd,dl,dt,figcaption,figure,picture,hr,img,li,main,ol,p,pre,ul,a,b,abbr,bdi,bdo,br,cite,code,data,dfn,em,i,kbd,mark,q,rp,rt,ruby,s,samp,small,span,strong,sub,sup,time,u,var,wbr,area,audio,map,track,video,embed,object,param,source,canvas,script,noscript,del,ins,caption,col,colgroup,table,thead,tbody,td,th,tr,button,datalist,fieldset,form,input,label,legend,meter,optgroup,option,output,progress,select,textarea,details,dialog,menu,summary,template,blockquote,iframe,tfoot\";\nconst SVG_TAGS = \"svg,animate,animateMotion,animateTransform,circle,clipPath,color-profile,defs,desc,discard,ellipse,feBlend,feColorMatrix,feComponentTransfer,feComposite,feConvolveMatrix,feDiffuseLighting,feDisplacementMap,feDistantLight,feDropShadow,feFlood,feFuncA,feFuncB,feFuncG,feFuncR,feGaussianBlur,feImage,feMerge,feMergeNode,feMorphology,feOffset,fePointLight,feSpecularLighting,feSpotLight,feTile,feTurbulence,filter,foreignObject,g,hatch,hatchpath,image,line,linearGradient,marker,mask,mesh,meshgradient,meshpatch,meshrow,metadata,mpath,path,pattern,polygon,polyline,radialGradient,rect,set,solidcolor,stop,switch,symbol,text,textPath,title,tspan,unknown,use,view\";\nconst MATH_TAGS = \"annotation,annotation-xml,maction,maligngroup,malignmark,math,menclose,merror,mfenced,mfrac,mfraction,mglyph,mi,mlabeledtr,mlongdiv,mmultiscripts,mn,mo,mover,mpadded,mphantom,mprescripts,mroot,mrow,ms,mscarries,mscarry,msgroup,msline,mspace,msqrt,msrow,mstack,mstyle,msub,msubsup,msup,mtable,mtd,mtext,mtr,munder,munderover,none,semantics\";\nconst VOID_TAGS = \"area,base,br,col,embed,hr,img,input,link,meta,param,source,track,wbr\";\nconst isHTMLTag = /* @__PURE__ */ makeMap(HTML_TAGS);\nconst isSVGTag = /* @__PURE__ */ makeMap(SVG_TAGS);\nconst isMathMLTag = /* @__PURE__ */ makeMap(MATH_TAGS);\nconst isVoidTag = /* @__PURE__ */ makeMap(VOID_TAGS);\n\nconst specialBooleanAttrs = `itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly`;\nconst isSpecialBooleanAttr = /* @__PURE__ */ makeMap(specialBooleanAttrs);\nconst isBooleanAttr = /* @__PURE__ */ makeMap(\n specialBooleanAttrs + `,async,autofocus,autoplay,controls,default,defer,disabled,hidden,inert,loop,open,required,reversed,scoped,seamless,checked,muted,multiple,selected`\n);\nfunction includeBooleanAttr(value) {\n return !!value || value === \"\";\n}\nconst unsafeAttrCharRE = /[>/=\"'\\u0009\\u000a\\u000c\\u0020]/;\nconst attrValidationCache = {};\nfunction isSSRSafeAttrName(name) {\n if (attrValidationCache.hasOwnProperty(name)) {\n return attrValidationCache[name];\n }\n const isUnsafe = unsafeAttrCharRE.test(name);\n if (isUnsafe) {\n console.error(`unsafe attribute name: ${name}`);\n }\n return attrValidationCache[name] = !isUnsafe;\n}\nconst propsToAttrMap = {\n acceptCharset: \"accept-charset\",\n className: \"class\",\n htmlFor: \"for\",\n httpEquiv: \"http-equiv\"\n};\nconst isKnownHtmlAttr = /* @__PURE__ */ makeMap(\n `accept,accept-charset,accesskey,action,align,allow,alt,async,autocapitalize,autocomplete,autofocus,autoplay,background,bgcolor,border,buffered,capture,challenge,charset,checked,cite,class,code,codebase,color,cols,colspan,content,contenteditable,contextmenu,controls,coords,crossorigin,csp,data,datetime,decoding,default,defer,dir,dirname,disabled,download,draggable,dropzone,enctype,enterkeyhint,for,form,formaction,formenctype,formmethod,formnovalidate,formtarget,headers,height,hidden,high,href,hreflang,http-equiv,icon,id,importance,inert,integrity,ismap,itemprop,keytype,kind,label,lang,language,loading,list,loop,low,manifest,max,maxlength,minlength,media,min,multiple,muted,name,novalidate,open,optimum,pattern,ping,placeholder,poster,preload,radiogroup,readonly,referrerpolicy,rel,required,reversed,rows,rowspan,sandbox,scope,scoped,selected,shape,size,sizes,slot,span,spellcheck,src,srcdoc,srclang,srcset,start,step,style,summary,tabindex,target,title,translate,type,usemap,value,width,wrap`\n);\nconst isKnownSvgAttr = /* @__PURE__ */ makeMap(\n `xmlns,accent-height,accumulate,additive,alignment-baseline,alphabetic,amplitude,arabic-form,ascent,attributeName,attributeType,azimuth,baseFrequency,baseline-shift,baseProfile,bbox,begin,bias,by,calcMode,cap-height,class,clip,clipPathUnits,clip-path,clip-rule,color,color-interpolation,color-interpolation-filters,color-profile,color-rendering,contentScriptType,contentStyleType,crossorigin,cursor,cx,cy,d,decelerate,descent,diffuseConstant,direction,display,divisor,dominant-baseline,dur,dx,dy,edgeMode,elevation,enable-background,end,exponent,fill,fill-opacity,fill-rule,filter,filterRes,filterUnits,flood-color,flood-opacity,font-family,font-size,font-size-adjust,font-stretch,font-style,font-variant,font-weight,format,from,fr,fx,fy,g1,g2,glyph-name,glyph-orientation-horizontal,glyph-orientation-vertical,glyphRef,gradientTransform,gradientUnits,hanging,height,href,hreflang,horiz-adv-x,horiz-origin-x,id,ideographic,image-rendering,in,in2,intercept,k,k1,k2,k3,k4,kernelMatrix,kernelUnitLength,kerning,keyPoints,keySplines,keyTimes,lang,lengthAdjust,letter-spacing,lighting-color,limitingConeAngle,local,marker-end,marker-mid,marker-start,markerHeight,markerUnits,markerWidth,mask,maskContentUnits,maskUnits,mathematical,max,media,method,min,mode,name,numOctaves,offset,opacity,operator,order,orient,orientation,origin,overflow,overline-position,overline-thickness,panose-1,paint-order,path,pathLength,patternContentUnits,patternTransform,patternUnits,ping,pointer-events,points,pointsAtX,pointsAtY,pointsAtZ,preserveAlpha,preserveAspectRatio,primitiveUnits,r,radius,referrerPolicy,refX,refY,rel,rendering-intent,repeatCount,repeatDur,requiredExtensions,requiredFeatures,restart,result,rotate,rx,ry,scale,seed,shape-rendering,slope,spacing,specularConstant,specularExponent,speed,spreadMethod,startOffset,stdDeviation,stemh,stemv,stitchTiles,stop-color,stop-opacity,strikethrough-position,strikethrough-thickness,string,stroke,stroke-dasharray,stroke-dashoffset,stroke-linecap,stroke-linejoin,stroke-miterlimit,stroke-opacity,stroke-width,style,surfaceScale,systemLanguage,tabindex,tableValues,target,targetX,targetY,text-anchor,text-decoration,text-rendering,textLength,to,transform,transform-origin,type,u1,u2,underline-position,underline-thickness,unicode,unicode-bidi,unicode-range,units-per-em,v-alphabetic,v-hanging,v-ideographic,v-mathematical,values,vector-effect,version,vert-adv-y,vert-origin-x,vert-origin-y,viewBox,viewTarget,visibility,width,widths,word-spacing,writing-mode,x,x-height,x1,x2,xChannelSelector,xlink:actuate,xlink:arcrole,xlink:href,xlink:role,xlink:show,xlink:title,xlink:type,xmlns:xlink,xml:base,xml:lang,xml:space,y,y1,y2,yChannelSelector,z,zoomAndPan`\n);\nfunction isRenderableAttrValue(value) {\n if (value == null) {\n return false;\n }\n const type = typeof value;\n return type === \"string\" || type === \"number\" || type === \"boolean\";\n}\n\nconst escapeRE = /[\"'&<>]/;\nfunction escapeHtml(string) {\n const str = \"\" + string;\n const match = escapeRE.exec(str);\n if (!match) {\n return str;\n }\n let html = \"\";\n let escaped;\n let index;\n let lastIndex = 0;\n for (index = match.index; index < str.length; index++) {\n switch (str.charCodeAt(index)) {\n case 34:\n escaped = \""\";\n break;\n case 38:\n escaped = \"&\";\n break;\n case 39:\n escaped = \"'\";\n break;\n case 60:\n escaped = \"<\";\n break;\n case 62:\n escaped = \">\";\n break;\n default:\n continue;\n }\n if (lastIndex !== index) {\n html += str.slice(lastIndex, index);\n }\n lastIndex = index + 1;\n html += escaped;\n }\n return lastIndex !== index ? html + str.slice(lastIndex, index) : html;\n}\nconst commentStripRE = /^-?>||--!>| looseEqual(item, val));\n}\n\nconst toDisplayString = (val) => {\n return isString(val) ? val : val == null ? \"\" : isArray(val) || isObject(val) && (val.toString === objectToString || !isFunction(val.toString)) ? JSON.stringify(val, replacer, 2) : String(val);\n};\nconst replacer = (_key, val) => {\n if (val && val.__v_isRef) {\n return replacer(_key, val.value);\n } else if (isMap(val)) {\n return {\n [`Map(${val.size})`]: [...val.entries()].reduce(\n (entries, [key, val2], i) => {\n entries[stringifySymbol(key, i) + \" =>\"] = val2;\n return entries;\n },\n {}\n )\n };\n } else if (isSet(val)) {\n return {\n [`Set(${val.size})`]: [...val.values()].map((v) => stringifySymbol(v))\n };\n } else if (isSymbol(val)) {\n return stringifySymbol(val);\n } else if (isObject(val) && !isArray(val) && !isPlainObject(val)) {\n return String(val);\n }\n return val;\n};\nconst stringifySymbol = (v, i = \"\") => {\n var _a;\n return isSymbol(v) ? `Symbol(${(_a = v.description) != null ? _a : i})` : v;\n};\n\nexport { EMPTY_ARR, EMPTY_OBJ, NO, NOOP, PatchFlagNames, PatchFlags, ShapeFlags, SlotFlags, camelize, capitalize, def, escapeHtml, escapeHtmlComment, extend, genPropsAccessExp, generateCodeFrame, getGlobalThis, hasChanged, hasOwn, hyphenate, includeBooleanAttr, invokeArrayFns, isArray, isBooleanAttr, isBuiltInDirective, isDate, isFunction, isGloballyAllowed, isGloballyWhitelisted, isHTMLTag, isIntegerKey, isKnownHtmlAttr, isKnownSvgAttr, isMap, isMathMLTag, isModelListener, isObject, isOn, isPlainObject, isPromise, isRegExp, isRenderableAttrValue, isReservedProp, isSSRSafeAttrName, isSVGTag, isSet, isSpecialBooleanAttr, isString, isSymbol, isVoidTag, looseEqual, looseIndexOf, looseToNumber, makeMap, normalizeClass, normalizeProps, normalizeStyle, objectToString, parseStringStyle, propsToAttrMap, remove, slotFlagsText, stringifyStyle, toDisplayString, toHandlerKey, toNumber, toRawType, toTypeString };\n","/**\n* @vue/reactivity v3.4.15\n* (c) 2018-present Yuxi (Evan) You and Vue contributors\n* @license MIT\n**/\nimport { NOOP, extend, isArray, isSymbol, isMap, isIntegerKey, hasOwn, hasChanged, isObject, makeMap, capitalize, toRawType, def, isFunction } from '@vue/shared';\n\nfunction warn(msg, ...args) {\n console.warn(`[Vue warn] ${msg}`, ...args);\n}\n\nlet activeEffectScope;\nclass EffectScope {\n constructor(detached = false) {\n this.detached = detached;\n /**\n * @internal\n */\n this._active = true;\n /**\n * @internal\n */\n this.effects = [];\n /**\n * @internal\n */\n this.cleanups = [];\n this.parent = activeEffectScope;\n if (!detached && activeEffectScope) {\n this.index = (activeEffectScope.scopes || (activeEffectScope.scopes = [])).push(\n this\n ) - 1;\n }\n }\n get active() {\n return this._active;\n }\n run(fn) {\n if (this._active) {\n const currentEffectScope = activeEffectScope;\n try {\n activeEffectScope = this;\n return fn();\n } finally {\n activeEffectScope = currentEffectScope;\n }\n } else if (!!(process.env.NODE_ENV !== \"production\")) {\n warn(`cannot run an inactive effect scope.`);\n }\n }\n /**\n * This should only be called on non-detached scopes\n * @internal\n */\n on() {\n activeEffectScope = this;\n }\n /**\n * This should only be called on non-detached scopes\n * @internal\n */\n off() {\n activeEffectScope = this.parent;\n }\n stop(fromParent) {\n if (this._active) {\n let i, l;\n for (i = 0, l = this.effects.length; i < l; i++) {\n this.effects[i].stop();\n }\n for (i = 0, l = this.cleanups.length; i < l; i++) {\n this.cleanups[i]();\n }\n if (this.scopes) {\n for (i = 0, l = this.scopes.length; i < l; i++) {\n this.scopes[i].stop(true);\n }\n }\n if (!this.detached && this.parent && !fromParent) {\n const last = this.parent.scopes.pop();\n if (last && last !== this) {\n this.parent.scopes[this.index] = last;\n last.index = this.index;\n }\n }\n this.parent = void 0;\n this._active = false;\n }\n }\n}\nfunction effectScope(detached) {\n return new EffectScope(detached);\n}\nfunction recordEffectScope(effect, scope = activeEffectScope) {\n if (scope && scope.active) {\n scope.effects.push(effect);\n }\n}\nfunction getCurrentScope() {\n return activeEffectScope;\n}\nfunction onScopeDispose(fn) {\n if (activeEffectScope) {\n activeEffectScope.cleanups.push(fn);\n } else if (!!(process.env.NODE_ENV !== \"production\")) {\n warn(\n `onScopeDispose() is called when there is no active effect scope to be associated with.`\n );\n }\n}\n\nlet activeEffect;\nclass ReactiveEffect {\n constructor(fn, trigger, scheduler, scope) {\n this.fn = fn;\n this.trigger = trigger;\n this.scheduler = scheduler;\n this.active = true;\n this.deps = [];\n /**\n * @internal\n */\n this._dirtyLevel = 2;\n /**\n * @internal\n */\n this._trackId = 0;\n /**\n * @internal\n */\n this._runnings = 0;\n /**\n * @internal\n */\n this._shouldSchedule = false;\n /**\n * @internal\n */\n this._depsLength = 0;\n recordEffectScope(this, scope);\n }\n get dirty() {\n if (this._dirtyLevel === 1) {\n pauseTracking();\n for (let i = 0; i < this._depsLength; i++) {\n const dep = this.deps[i];\n if (dep.computed) {\n triggerComputed(dep.computed);\n if (this._dirtyLevel >= 2) {\n break;\n }\n }\n }\n if (this._dirtyLevel < 2) {\n this._dirtyLevel = 0;\n }\n resetTracking();\n }\n return this._dirtyLevel >= 2;\n }\n set dirty(v) {\n this._dirtyLevel = v ? 2 : 0;\n }\n run() {\n this._dirtyLevel = 0;\n if (!this.active) {\n return this.fn();\n }\n let lastShouldTrack = shouldTrack;\n let lastEffect = activeEffect;\n try {\n shouldTrack = true;\n activeEffect = this;\n this._runnings++;\n preCleanupEffect(this);\n return this.fn();\n } finally {\n postCleanupEffect(this);\n this._runnings--;\n activeEffect = lastEffect;\n shouldTrack = lastShouldTrack;\n }\n }\n stop() {\n var _a;\n if (this.active) {\n preCleanupEffect(this);\n postCleanupEffect(this);\n (_a = this.onStop) == null ? void 0 : _a.call(this);\n this.active = false;\n }\n }\n}\nfunction triggerComputed(computed) {\n return computed.value;\n}\nfunction preCleanupEffect(effect2) {\n effect2._trackId++;\n effect2._depsLength = 0;\n}\nfunction postCleanupEffect(effect2) {\n if (effect2.deps && effect2.deps.length > effect2._depsLength) {\n for (let i = effect2._depsLength; i < effect2.deps.length; i++) {\n cleanupDepEffect(effect2.deps[i], effect2);\n }\n effect2.deps.length = effect2._depsLength;\n }\n}\nfunction cleanupDepEffect(dep, effect2) {\n const trackId = dep.get(effect2);\n if (trackId !== void 0 && effect2._trackId !== trackId) {\n dep.delete(effect2);\n if (dep.size === 0) {\n dep.cleanup();\n }\n }\n}\nfunction effect(fn, options) {\n if (fn.effect instanceof ReactiveEffect) {\n fn = fn.effect.fn;\n }\n const _effect = new ReactiveEffect(fn, NOOP, () => {\n if (_effect.dirty) {\n _effect.run();\n }\n });\n if (options) {\n extend(_effect, options);\n if (options.scope)\n recordEffectScope(_effect, options.scope);\n }\n if (!options || !options.lazy) {\n _effect.run();\n }\n const runner = _effect.run.bind(_effect);\n runner.effect = _effect;\n return runner;\n}\nfunction stop(runner) {\n runner.effect.stop();\n}\nlet shouldTrack = true;\nlet pauseScheduleStack = 0;\nconst trackStack = [];\nfunction pauseTracking() {\n trackStack.push(shouldTrack);\n shouldTrack = false;\n}\nfunction enableTracking() {\n trackStack.push(shouldTrack);\n shouldTrack = true;\n}\nfunction resetTracking() {\n const last = trackStack.pop();\n shouldTrack = last === void 0 ? true : last;\n}\nfunction pauseScheduling() {\n pauseScheduleStack++;\n}\nfunction resetScheduling() {\n pauseScheduleStack--;\n while (!pauseScheduleStack && queueEffectSchedulers.length) {\n queueEffectSchedulers.shift()();\n }\n}\nfunction trackEffect(effect2, dep, debuggerEventExtraInfo) {\n var _a;\n if (dep.get(effect2) !== effect2._trackId) {\n dep.set(effect2, effect2._trackId);\n const oldDep = effect2.deps[effect2._depsLength];\n if (oldDep !== dep) {\n if (oldDep) {\n cleanupDepEffect(oldDep, effect2);\n }\n effect2.deps[effect2._depsLength++] = dep;\n } else {\n effect2._depsLength++;\n }\n if (!!(process.env.NODE_ENV !== \"production\")) {\n (_a = effect2.onTrack) == null ? void 0 : _a.call(effect2, extend({ effect: effect2 }, debuggerEventExtraInfo));\n }\n }\n}\nconst queueEffectSchedulers = [];\nfunction triggerEffects(dep, dirtyLevel, debuggerEventExtraInfo) {\n var _a;\n pauseScheduling();\n for (const effect2 of dep.keys()) {\n if (effect2._dirtyLevel < dirtyLevel && dep.get(effect2) === effect2._trackId) {\n const lastDirtyLevel = effect2._dirtyLevel;\n effect2._dirtyLevel = dirtyLevel;\n if (lastDirtyLevel === 0) {\n effect2._shouldSchedule = true;\n if (!!(process.env.NODE_ENV !== \"production\")) {\n (_a = effect2.onTrigger) == null ? void 0 : _a.call(effect2, extend({ effect: effect2 }, debuggerEventExtraInfo));\n }\n effect2.trigger();\n }\n }\n }\n scheduleEffects(dep);\n resetScheduling();\n}\nfunction scheduleEffects(dep) {\n for (const effect2 of dep.keys()) {\n if (effect2.scheduler && effect2._shouldSchedule && (!effect2._runnings || effect2.allowRecurse) && dep.get(effect2) === effect2._trackId) {\n effect2._shouldSchedule = false;\n queueEffectSchedulers.push(effect2.scheduler);\n }\n }\n}\n\nconst createDep = (cleanup, computed) => {\n const dep = /* @__PURE__ */ new Map();\n dep.cleanup = cleanup;\n dep.computed = computed;\n return dep;\n};\n\nconst targetMap = /* @__PURE__ */ new WeakMap();\nconst ITERATE_KEY = Symbol(!!(process.env.NODE_ENV !== \"production\") ? \"iterate\" : \"\");\nconst MAP_KEY_ITERATE_KEY = Symbol(!!(process.env.NODE_ENV !== \"production\") ? \"Map key iterate\" : \"\");\nfunction track(target, type, key) {\n if (shouldTrack && activeEffect) {\n let depsMap = targetMap.get(target);\n if (!depsMap) {\n targetMap.set(target, depsMap = /* @__PURE__ */ new Map());\n }\n let dep = depsMap.get(key);\n if (!dep) {\n depsMap.set(key, dep = createDep(() => depsMap.delete(key)));\n }\n trackEffect(\n activeEffect,\n dep,\n !!(process.env.NODE_ENV !== \"production\") ? {\n target,\n type,\n key\n } : void 0\n );\n }\n}\nfunction trigger(target, type, key, newValue, oldValue, oldTarget) {\n const depsMap = targetMap.get(target);\n if (!depsMap) {\n return;\n }\n let deps = [];\n if (type === \"clear\") {\n deps = [...depsMap.values()];\n } else if (key === \"length\" && isArray(target)) {\n const newLength = Number(newValue);\n depsMap.forEach((dep, key2) => {\n if (key2 === \"length\" || !isSymbol(key2) && key2 >= newLength) {\n deps.push(dep);\n }\n });\n } else {\n if (key !== void 0) {\n deps.push(depsMap.get(key));\n }\n switch (type) {\n case \"add\":\n if (!isArray(target)) {\n deps.push(depsMap.get(ITERATE_KEY));\n if (isMap(target)) {\n deps.push(depsMap.get(MAP_KEY_ITERATE_KEY));\n }\n } else if (isIntegerKey(key)) {\n deps.push(depsMap.get(\"length\"));\n }\n break;\n case \"delete\":\n if (!isArray(target)) {\n deps.push(depsMap.get(ITERATE_KEY));\n if (isMap(target)) {\n deps.push(depsMap.get(MAP_KEY_ITERATE_KEY));\n }\n }\n break;\n case \"set\":\n if (isMap(target)) {\n deps.push(depsMap.get(ITERATE_KEY));\n }\n break;\n }\n }\n pauseScheduling();\n for (const dep of deps) {\n if (dep) {\n triggerEffects(\n dep,\n 2,\n !!(process.env.NODE_ENV !== \"production\") ? {\n target,\n type,\n key,\n newValue,\n oldValue,\n oldTarget\n } : void 0\n );\n }\n }\n resetScheduling();\n}\nfunction getDepFromReactive(object, key) {\n var _a;\n return (_a = targetMap.get(object)) == null ? void 0 : _a.get(key);\n}\n\nconst isNonTrackableKeys = /* @__PURE__ */ makeMap(`__proto__,__v_isRef,__isVue`);\nconst builtInSymbols = new Set(\n /* @__PURE__ */ Object.getOwnPropertyNames(Symbol).filter((key) => key !== \"arguments\" && key !== \"caller\").map((key) => Symbol[key]).filter(isSymbol)\n);\nconst arrayInstrumentations = /* @__PURE__ */ createArrayInstrumentations();\nfunction createArrayInstrumentations() {\n const instrumentations = {};\n [\"includes\", \"indexOf\", \"lastIndexOf\"].forEach((key) => {\n instrumentations[key] = function(...args) {\n const arr = toRaw(this);\n for (let i = 0, l = this.length; i < l; i++) {\n track(arr, \"get\", i + \"\");\n }\n const res = arr[key](...args);\n if (res === -1 || res === false) {\n return arr[key](...args.map(toRaw));\n } else {\n return res;\n }\n };\n });\n [\"push\", \"pop\", \"shift\", \"unshift\", \"splice\"].forEach((key) => {\n instrumentations[key] = function(...args) {\n pauseTracking();\n pauseScheduling();\n const res = toRaw(this)[key].apply(this, args);\n resetScheduling();\n resetTracking();\n return res;\n };\n });\n return instrumentations;\n}\nfunction hasOwnProperty(key) {\n const obj = toRaw(this);\n track(obj, \"has\", key);\n return obj.hasOwnProperty(key);\n}\nclass BaseReactiveHandler {\n constructor(_isReadonly = false, _shallow = false) {\n this._isReadonly = _isReadonly;\n this._shallow = _shallow;\n }\n get(target, key, receiver) {\n const isReadonly2 = this._isReadonly, shallow = this._shallow;\n if (key === \"__v_isReactive\") {\n return !isReadonly2;\n } else if (key === \"__v_isReadonly\") {\n return isReadonly2;\n } else if (key === \"__v_isShallow\") {\n return shallow;\n } else if (key === \"__v_raw\") {\n if (receiver === (isReadonly2 ? shallow ? shallowReadonlyMap : readonlyMap : shallow ? shallowReactiveMap : reactiveMap).get(target) || // receiver is not the reactive proxy, but has the same prototype\n // this means the reciever is a user proxy of the reactive proxy\n Object.getPrototypeOf(target) === Object.getPrototypeOf(receiver)) {\n return target;\n }\n return;\n }\n const targetIsArray = isArray(target);\n if (!isReadonly2) {\n if (targetIsArray && hasOwn(arrayInstrumentations, key)) {\n return Reflect.get(arrayInstrumentations, key, receiver);\n }\n if (key === \"hasOwnProperty\") {\n return hasOwnProperty;\n }\n }\n const res = Reflect.get(target, key, receiver);\n if (isSymbol(key) ? builtInSymbols.has(key) : isNonTrackableKeys(key)) {\n return res;\n }\n if (!isReadonly2) {\n track(target, \"get\", key);\n }\n if (shallow) {\n return res;\n }\n if (isRef(res)) {\n return targetIsArray && isIntegerKey(key) ? res : res.value;\n }\n if (isObject(res)) {\n return isReadonly2 ? readonly(res) : reactive(res);\n }\n return res;\n }\n}\nclass MutableReactiveHandler extends BaseReactiveHandler {\n constructor(shallow = false) {\n super(false, shallow);\n }\n set(target, key, value, receiver) {\n let oldValue = target[key];\n if (!this._shallow) {\n const isOldValueReadonly = isReadonly(oldValue);\n if (!isShallow(value) && !isReadonly(value)) {\n oldValue = toRaw(oldValue);\n value = toRaw(value);\n }\n if (!isArray(target) && isRef(oldValue) && !isRef(value)) {\n if (isOldValueReadonly) {\n return false;\n } else {\n oldValue.value = value;\n return true;\n }\n }\n }\n const hadKey = isArray(target) && isIntegerKey(key) ? Number(key) < target.length : hasOwn(target, key);\n const result = Reflect.set(target, key, value, receiver);\n if (target === toRaw(receiver)) {\n if (!hadKey) {\n trigger(target, \"add\", key, value);\n } else if (hasChanged(value, oldValue)) {\n trigger(target, \"set\", key, value, oldValue);\n }\n }\n return result;\n }\n deleteProperty(target, key) {\n const hadKey = hasOwn(target, key);\n const oldValue = target[key];\n const result = Reflect.deleteProperty(target, key);\n if (result && hadKey) {\n trigger(target, \"delete\", key, void 0, oldValue);\n }\n return result;\n }\n has(target, key) {\n const result = Reflect.has(target, key);\n if (!isSymbol(key) || !builtInSymbols.has(key)) {\n track(target, \"has\", key);\n }\n return result;\n }\n ownKeys(target) {\n track(\n target,\n \"iterate\",\n isArray(target) ? \"length\" : ITERATE_KEY\n );\n return Reflect.ownKeys(target);\n }\n}\nclass ReadonlyReactiveHandler extends BaseReactiveHandler {\n constructor(shallow = false) {\n super(true, shallow);\n }\n set(target, key) {\n if (!!(process.env.NODE_ENV !== \"production\")) {\n warn(\n `Set operation on key \"${String(key)}\" failed: target is readonly.`,\n target\n );\n }\n return true;\n }\n deleteProperty(target, key) {\n if (!!(process.env.NODE_ENV !== \"production\")) {\n warn(\n `Delete operation on key \"${String(key)}\" failed: target is readonly.`,\n target\n );\n }\n return true;\n }\n}\nconst mutableHandlers = /* @__PURE__ */ new MutableReactiveHandler();\nconst readonlyHandlers = /* @__PURE__ */ new ReadonlyReactiveHandler();\nconst shallowReactiveHandlers = /* @__PURE__ */ new MutableReactiveHandler(\n true\n);\nconst shallowReadonlyHandlers = /* @__PURE__ */ new ReadonlyReactiveHandler(true);\n\nconst toShallow = (value) => value;\nconst getProto = (v) => Reflect.getPrototypeOf(v);\nfunction get(target, key, isReadonly = false, isShallow = false) {\n target = target[\"__v_raw\"];\n const rawTarget = toRaw(target);\n const rawKey = toRaw(key);\n if (!isReadonly) {\n if (hasChanged(key, rawKey)) {\n track(rawTarget, \"get\", key);\n }\n track(rawTarget, \"get\", rawKey);\n }\n const { has: has2 } = getProto(rawTarget);\n const wrap = isShallow ? toShallow : isReadonly ? toReadonly : toReactive;\n if (has2.call(rawTarget, key)) {\n return wrap(target.get(key));\n } else if (has2.call(rawTarget, rawKey)) {\n return wrap(target.get(rawKey));\n } else if (target !== rawTarget) {\n target.get(key);\n }\n}\nfunction has(key, isReadonly = false) {\n const target = this[\"__v_raw\"];\n const rawTarget = toRaw(target);\n const rawKey = toRaw(key);\n if (!isReadonly) {\n if (hasChanged(key, rawKey)) {\n track(rawTarget, \"has\", key);\n }\n track(rawTarget, \"has\", rawKey);\n }\n return key === rawKey ? target.has(key) : target.has(key) || target.has(rawKey);\n}\nfunction size(target, isReadonly = false) {\n target = target[\"__v_raw\"];\n !isReadonly && track(toRaw(target), \"iterate\", ITERATE_KEY);\n return Reflect.get(target, \"size\", target);\n}\nfunction add(value) {\n value = toRaw(value);\n const target = toRaw(this);\n const proto = getProto(target);\n const hadKey = proto.has.call(target, value);\n if (!hadKey) {\n target.add(value);\n trigger(target, \"add\", value, value);\n }\n return this;\n}\nfunction set(key, value) {\n value = toRaw(value);\n const target = toRaw(this);\n const { has: has2, get: get2 } = getProto(target);\n let hadKey = has2.call(target, key);\n if (!hadKey) {\n key = toRaw(key);\n hadKey = has2.call(target, key);\n } else if (!!(process.env.NODE_ENV !== \"production\")) {\n checkIdentityKeys(target, has2, key);\n }\n const oldValue = get2.call(target, key);\n target.set(key, value);\n if (!hadKey) {\n trigger(target, \"add\", key, value);\n } else if (hasChanged(value, oldValue)) {\n trigger(target, \"set\", key, value, oldValue);\n }\n return this;\n}\nfunction deleteEntry(key) {\n const target = toRaw(this);\n const { has: has2, get: get2 } = getProto(target);\n let hadKey = has2.call(target, key);\n if (!hadKey) {\n key = toRaw(key);\n hadKey = has2.call(target, key);\n } else if (!!(process.env.NODE_ENV !== \"production\")) {\n checkIdentityKeys(target, has2, key);\n }\n const oldValue = get2 ? get2.call(target, key) : void 0;\n const result = target.delete(key);\n if (hadKey) {\n trigger(target, \"delete\", key, void 0, oldValue);\n }\n return result;\n}\nfunction clear() {\n const target = toRaw(this);\n const hadItems = target.size !== 0;\n const oldTarget = !!(process.env.NODE_ENV !== \"production\") ? isMap(target) ? new Map(target) : new Set(target) : void 0;\n const result = target.clear();\n if (hadItems) {\n trigger(target, \"clear\", void 0, void 0, oldTarget);\n }\n return result;\n}\nfunction createForEach(isReadonly, isShallow) {\n return function forEach(callback, thisArg) {\n const observed = this;\n const target = observed[\"__v_raw\"];\n const rawTarget = toRaw(target);\n const wrap = isShallow ? toShallow : isReadonly ? toReadonly : toReactive;\n !isReadonly && track(rawTarget, \"iterate\", ITERATE_KEY);\n return target.forEach((value, key) => {\n return callback.call(thisArg, wrap(value), wrap(key), observed);\n });\n };\n}\nfunction createIterableMethod(method, isReadonly, isShallow) {\n return function(...args) {\n const target = this[\"__v_raw\"];\n const rawTarget = toRaw(target);\n const targetIsMap = isMap(rawTarget);\n const isPair = method === \"entries\" || method === Symbol.iterator && targetIsMap;\n const isKeyOnly = method === \"keys\" && targetIsMap;\n const innerIterator = target[method](...args);\n const wrap = isShallow ? toShallow : isReadonly ? toReadonly : toReactive;\n !isReadonly && track(\n rawTarget,\n \"iterate\",\n isKeyOnly ? MAP_KEY_ITERATE_KEY : ITERATE_KEY\n );\n return {\n // iterator protocol\n next() {\n const { value, done } = innerIterator.next();\n return done ? { value, done } : {\n value: isPair ? [wrap(value[0]), wrap(value[1])] : wrap(value),\n done\n };\n },\n // iterable protocol\n [Symbol.iterator]() {\n return this;\n }\n };\n };\n}\nfunction createReadonlyMethod(type) {\n return function(...args) {\n if (!!(process.env.NODE_ENV !== \"production\")) {\n const key = args[0] ? `on key \"${args[0]}\" ` : ``;\n console.warn(\n `${capitalize(type)} operation ${key}failed: target is readonly.`,\n toRaw(this)\n );\n }\n return type === \"delete\" ? false : type === \"clear\" ? void 0 : this;\n };\n}\nfunction createInstrumentations() {\n const mutableInstrumentations2 = {\n get(key) {\n return get(this, key);\n },\n get size() {\n return size(this);\n },\n has,\n add,\n set,\n delete: deleteEntry,\n clear,\n forEach: createForEach(false, false)\n };\n const shallowInstrumentations2 = {\n get(key) {\n return get(this, key, false, true);\n },\n get size() {\n return size(this);\n },\n has,\n add,\n set,\n delete: deleteEntry,\n clear,\n forEach: createForEach(false, true)\n };\n const readonlyInstrumentations2 = {\n get(key) {\n return get(this, key, true);\n },\n get size() {\n return size(this, true);\n },\n has(key) {\n return has.call(this, key, true);\n },\n add: createReadonlyMethod(\"add\"),\n set: createReadonlyMethod(\"set\"),\n delete: createReadonlyMethod(\"delete\"),\n clear: createReadonlyMethod(\"clear\"),\n forEach: createForEach(true, false)\n };\n const shallowReadonlyInstrumentations2 = {\n get(key) {\n return get(this, key, true, true);\n },\n get size() {\n return size(this, true);\n },\n has(key) {\n return has.call(this, key, true);\n },\n add: createReadonlyMethod(\"add\"),\n set: createReadonlyMethod(\"set\"),\n delete: createReadonlyMethod(\"delete\"),\n clear: createReadonlyMethod(\"clear\"),\n forEach: createForEach(true, true)\n };\n const iteratorMethods = [\"keys\", \"values\", \"entries\", Symbol.iterator];\n iteratorMethods.forEach((method) => {\n mutableInstrumentations2[method] = createIterableMethod(\n method,\n false,\n false\n );\n readonlyInstrumentations2[method] = createIterableMethod(\n method,\n true,\n false\n );\n shallowInstrumentations2[method] = createIterableMethod(\n method,\n false,\n true\n );\n shallowReadonlyInstrumentations2[method] = createIterableMethod(\n method,\n true,\n true\n );\n });\n return [\n mutableInstrumentations2,\n readonlyInstrumentations2,\n shallowInstrumentations2,\n shallowReadonlyInstrumentations2\n ];\n}\nconst [\n mutableInstrumentations,\n readonlyInstrumentations,\n shallowInstrumentations,\n shallowReadonlyInstrumentations\n] = /* @__PURE__ */ createInstrumentations();\nfunction createInstrumentationGetter(isReadonly, shallow) {\n const instrumentations = shallow ? isReadonly ? shallowReadonlyInstrumentations : shallowInstrumentations : isReadonly ? readonlyInstrumentations : mutableInstrumentations;\n return (target, key, receiver) => {\n if (key === \"__v_isReactive\") {\n return !isReadonly;\n } else if (key === \"__v_isReadonly\") {\n return isReadonly;\n } else if (key === \"__v_raw\") {\n return target;\n }\n return Reflect.get(\n hasOwn(instrumentations, key) && key in target ? instrumentations : target,\n key,\n receiver\n );\n };\n}\nconst mutableCollectionHandlers = {\n get: /* @__PURE__ */ createInstrumentationGetter(false, false)\n};\nconst shallowCollectionHandlers = {\n get: /* @__PURE__ */ createInstrumentationGetter(false, true)\n};\nconst readonlyCollectionHandlers = {\n get: /* @__PURE__ */ createInstrumentationGetter(true, false)\n};\nconst shallowReadonlyCollectionHandlers = {\n get: /* @__PURE__ */ createInstrumentationGetter(true, true)\n};\nfunction checkIdentityKeys(target, has2, key) {\n const rawKey = toRaw(key);\n if (rawKey !== key && has2.call(target, rawKey)) {\n const type = toRawType(target);\n console.warn(\n `Reactive ${type} contains both the raw and reactive versions of the same object${type === `Map` ? ` as keys` : ``}, which can lead to inconsistencies. Avoid differentiating between the raw and reactive versions of an object and only use the reactive version if possible.`\n );\n }\n}\n\nconst reactiveMap = /* @__PURE__ */ new WeakMap();\nconst shallowReactiveMap = /* @__PURE__ */ new WeakMap();\nconst readonlyMap = /* @__PURE__ */ new WeakMap();\nconst shallowReadonlyMap = /* @__PURE__ */ new WeakMap();\nfunction targetTypeMap(rawType) {\n switch (rawType) {\n case \"Object\":\n case \"Array\":\n return 1 /* COMMON */;\n case \"Map\":\n case \"Set\":\n case \"WeakMap\":\n case \"WeakSet\":\n return 2 /* COLLECTION */;\n default:\n return 0 /* INVALID */;\n }\n}\nfunction getTargetType(value) {\n return value[\"__v_skip\"] || !Object.isExtensible(value) ? 0 /* INVALID */ : targetTypeMap(toRawType(value));\n}\nfunction reactive(target) {\n if (isReadonly(target)) {\n return target;\n }\n return createReactiveObject(\n target,\n false,\n mutableHandlers,\n mutableCollectionHandlers,\n reactiveMap\n );\n}\nfunction shallowReactive(target) {\n return createReactiveObject(\n target,\n false,\n shallowReactiveHandlers,\n shallowCollectionHandlers,\n shallowReactiveMap\n );\n}\nfunction readonly(target) {\n return createReactiveObject(\n target,\n true,\n readonlyHandlers,\n readonlyCollectionHandlers,\n readonlyMap\n );\n}\nfunction shallowReadonly(target) {\n return createReactiveObject(\n target,\n true,\n shallowReadonlyHandlers,\n shallowReadonlyCollectionHandlers,\n shallowReadonlyMap\n );\n}\nfunction createReactiveObject(target, isReadonly2, baseHandlers, collectionHandlers, proxyMap) {\n if (!isObject(target)) {\n if (!!(process.env.NODE_ENV !== \"production\")) {\n console.warn(`value cannot be made reactive: ${String(target)}`);\n }\n return target;\n }\n if (target[\"__v_raw\"] && !(isReadonly2 && target[\"__v_isReactive\"])) {\n return target;\n }\n const existingProxy = proxyMap.get(target);\n if (existingProxy) {\n return existingProxy;\n }\n const targetType = getTargetType(target);\n if (targetType === 0 /* INVALID */) {\n return target;\n }\n const proxy = new Proxy(\n target,\n targetType === 2 /* COLLECTION */ ? collectionHandlers : baseHandlers\n );\n proxyMap.set(target, proxy);\n return proxy;\n}\nfunction isReactive(value) {\n if (isReadonly(value)) {\n return isReactive(value[\"__v_raw\"]);\n }\n return !!(value && value[\"__v_isReactive\"]);\n}\nfunction isReadonly(value) {\n return !!(value && value[\"__v_isReadonly\"]);\n}\nfunction isShallow(value) {\n return !!(value && value[\"__v_isShallow\"]);\n}\nfunction isProxy(value) {\n return isReactive(value) || isReadonly(value);\n}\nfunction toRaw(observed) {\n const raw = observed && observed[\"__v_raw\"];\n return raw ? toRaw(raw) : observed;\n}\nfunction markRaw(value) {\n def(value, \"__v_skip\", true);\n return value;\n}\nconst toReactive = (value) => isObject(value) ? reactive(value) : value;\nconst toReadonly = (value) => isObject(value) ? readonly(value) : value;\n\nclass ComputedRefImpl {\n constructor(getter, _setter, isReadonly, isSSR) {\n this._setter = _setter;\n this.dep = void 0;\n this.__v_isRef = true;\n this[\"__v_isReadonly\"] = false;\n this.effect = new ReactiveEffect(\n () => getter(this._value),\n () => triggerRefValue(this, 1),\n () => this.dep && scheduleEffects(this.dep)\n );\n this.effect.computed = this;\n this.effect.active = this._cacheable = !isSSR;\n this[\"__v_isReadonly\"] = isReadonly;\n }\n get value() {\n const self = toRaw(this);\n if (!self._cacheable || self.effect.dirty) {\n if (hasChanged(self._value, self._value = self.effect.run())) {\n triggerRefValue(self, 2);\n }\n }\n trackRefValue(self);\n if (self.effect._dirtyLevel >= 1) {\n triggerRefValue(self, 1);\n }\n return self._value;\n }\n set value(newValue) {\n this._setter(newValue);\n }\n // #region polyfill _dirty for backward compatibility third party code for Vue <= 3.3.x\n get _dirty() {\n return this.effect.dirty;\n }\n set _dirty(v) {\n this.effect.dirty = v;\n }\n // #endregion\n}\nfunction computed(getterOrOptions, debugOptions, isSSR = false) {\n let getter;\n let setter;\n const onlyGetter = isFunction(getterOrOptions);\n if (onlyGetter) {\n getter = getterOrOptions;\n setter = !!(process.env.NODE_ENV !== \"production\") ? () => {\n console.warn(\"Write operation failed: computed value is readonly\");\n } : NOOP;\n } else {\n getter = getterOrOptions.get;\n setter = getterOrOptions.set;\n }\n const cRef = new ComputedRefImpl(getter, setter, onlyGetter || !setter, isSSR);\n if (!!(process.env.NODE_ENV !== \"production\") && debugOptions && !isSSR) {\n cRef.effect.onTrack = debugOptions.onTrack;\n cRef.effect.onTrigger = debugOptions.onTrigger;\n }\n return cRef;\n}\n\nfunction trackRefValue(ref2) {\n if (shouldTrack && activeEffect) {\n ref2 = toRaw(ref2);\n trackEffect(\n activeEffect,\n ref2.dep || (ref2.dep = createDep(\n () => ref2.dep = void 0,\n ref2 instanceof ComputedRefImpl ? ref2 : void 0\n )),\n !!(process.env.NODE_ENV !== \"production\") ? {\n target: ref2,\n type: \"get\",\n key: \"value\"\n } : void 0\n );\n }\n}\nfunction triggerRefValue(ref2, dirtyLevel = 2, newVal) {\n ref2 = toRaw(ref2);\n const dep = ref2.dep;\n if (dep) {\n triggerEffects(\n dep,\n dirtyLevel,\n !!(process.env.NODE_ENV !== \"production\") ? {\n target: ref2,\n type: \"set\",\n key: \"value\",\n newValue: newVal\n } : void 0\n );\n }\n}\nfunction isRef(r) {\n return !!(r && r.__v_isRef === true);\n}\nfunction ref(value) {\n return createRef(value, false);\n}\nfunction shallowRef(value) {\n return createRef(value, true);\n}\nfunction createRef(rawValue, shallow) {\n if (isRef(rawValue)) {\n return rawValue;\n }\n return new RefImpl(rawValue, shallow);\n}\nclass RefImpl {\n constructor(value, __v_isShallow) {\n this.__v_isShallow = __v_isShallow;\n this.dep = void 0;\n this.__v_isRef = true;\n this._rawValue = __v_isShallow ? value : toRaw(value);\n this._value = __v_isShallow ? value : toReactive(value);\n }\n get value() {\n trackRefValue(this);\n return this._value;\n }\n set value(newVal) {\n const useDirectValue = this.__v_isShallow || isShallow(newVal) || isReadonly(newVal);\n newVal = useDirectValue ? newVal : toRaw(newVal);\n if (hasChanged(newVal, this._rawValue)) {\n this._rawValue = newVal;\n this._value = useDirectValue ? newVal : toReactive(newVal);\n triggerRefValue(this, 2, newVal);\n }\n }\n}\nfunction triggerRef(ref2) {\n triggerRefValue(ref2, 2, !!(process.env.NODE_ENV !== \"production\") ? ref2.value : void 0);\n}\nfunction unref(ref2) {\n return isRef(ref2) ? ref2.value : ref2;\n}\nfunction toValue(source) {\n return isFunction(source) ? source() : unref(source);\n}\nconst shallowUnwrapHandlers = {\n get: (target, key, receiver) => unref(Reflect.get(target, key, receiver)),\n set: (target, key, value, receiver) => {\n const oldValue = target[key];\n if (isRef(oldValue) && !isRef(value)) {\n oldValue.value = value;\n return true;\n } else {\n return Reflect.set(target, key, value, receiver);\n }\n }\n};\nfunction proxyRefs(objectWithRefs) {\n return isReactive(objectWithRefs) ? objectWithRefs : new Proxy(objectWithRefs, shallowUnwrapHandlers);\n}\nclass CustomRefImpl {\n constructor(factory) {\n this.dep = void 0;\n this.__v_isRef = true;\n const { get, set } = factory(\n () => trackRefValue(this),\n () => triggerRefValue(this)\n );\n this._get = get;\n this._set = set;\n }\n get value() {\n return this._get();\n }\n set value(newVal) {\n this._set(newVal);\n }\n}\nfunction customRef(factory) {\n return new CustomRefImpl(factory);\n}\nfunction toRefs(object) {\n if (!!(process.env.NODE_ENV !== \"production\") && !isProxy(object)) {\n console.warn(`toRefs() expects a reactive object but received a plain one.`);\n }\n const ret = isArray(object) ? new Array(object.length) : {};\n for (const key in object) {\n ret[key] = propertyToRef(object, key);\n }\n return ret;\n}\nclass ObjectRefImpl {\n constructor(_object, _key, _defaultValue) {\n this._object = _object;\n this._key = _key;\n this._defaultValue = _defaultValue;\n this.__v_isRef = true;\n }\n get value() {\n const val = this._object[this._key];\n return val === void 0 ? this._defaultValue : val;\n }\n set value(newVal) {\n this._object[this._key] = newVal;\n }\n get dep() {\n return getDepFromReactive(toRaw(this._object), this._key);\n }\n}\nclass GetterRefImpl {\n constructor(_getter) {\n this._getter = _getter;\n this.__v_isRef = true;\n this.__v_isReadonly = true;\n }\n get value() {\n return this._getter();\n }\n}\nfunction toRef(source, key, defaultValue) {\n if (isRef(source)) {\n return source;\n } else if (isFunction(source)) {\n return new GetterRefImpl(source);\n } else if (isObject(source) && arguments.length > 1) {\n return propertyToRef(source, key, defaultValue);\n } else {\n return ref(source);\n }\n}\nfunction propertyToRef(source, key, defaultValue) {\n const val = source[key];\n return isRef(val) ? val : new ObjectRefImpl(source, key, defaultValue);\n}\n\nconst deferredComputed = computed;\n\nconst TrackOpTypes = {\n \"GET\": \"get\",\n \"HAS\": \"has\",\n \"ITERATE\": \"iterate\"\n};\nconst TriggerOpTypes = {\n \"SET\": \"set\",\n \"ADD\": \"add\",\n \"DELETE\": \"delete\",\n \"CLEAR\": \"clear\"\n};\nconst ReactiveFlags = {\n \"SKIP\": \"__v_skip\",\n \"IS_REACTIVE\": \"__v_isReactive\",\n \"IS_READONLY\": \"__v_isReadonly\",\n \"IS_SHALLOW\": \"__v_isShallow\",\n \"RAW\": \"__v_raw\"\n};\n\nexport { EffectScope, ITERATE_KEY, ReactiveEffect, ReactiveFlags, TrackOpTypes, TriggerOpTypes, computed, customRef, deferredComputed, effect, effectScope, enableTracking, getCurrentScope, isProxy, isReactive, isReadonly, isRef, isShallow, markRaw, onScopeDispose, pauseScheduling, pauseTracking, proxyRefs, reactive, readonly, ref, resetScheduling, resetTracking, shallowReactive, shallowReadonly, shallowRef, stop, toRaw, toRef, toRefs, toValue, track, trigger, triggerRef, unref };\n","/**\n* @vue/runtime-core v3.4.15\n* (c) 2018-present Yuxi (Evan) You and Vue contributors\n* @license MIT\n**/\nimport { pauseTracking, resetTracking, isRef, toRaw, isShallow as isShallow$1, isReactive, ReactiveEffect, getCurrentScope, ref, shallowReadonly, track, reactive, shallowReactive, trigger, isProxy, proxyRefs, markRaw, EffectScope, computed as computed$1, customRef, isReadonly } from '@vue/reactivity';\nexport { EffectScope, ReactiveEffect, TrackOpTypes, TriggerOpTypes, customRef, effect, effectScope, getCurrentScope, isProxy, isReactive, isReadonly, isRef, isShallow, markRaw, onScopeDispose, proxyRefs, reactive, readonly, ref, shallowReactive, shallowReadonly, shallowRef, stop, toRaw, toRef, toRefs, toValue, triggerRef, unref } from '@vue/reactivity';\nimport { isString, isFunction, isPromise, isArray, NOOP, getGlobalThis, extend, EMPTY_OBJ, toHandlerKey, looseToNumber, hyphenate, camelize, isObject, isOn, hasOwn, isModelListener, capitalize, toNumber, hasChanged, remove, isSet, isMap, isPlainObject, isBuiltInDirective, invokeArrayFns, isRegExp, isGloballyAllowed, NO, def, isReservedProp, EMPTY_ARR, toRawType, makeMap, normalizeClass, stringifyStyle, normalizeStyle, isKnownSvgAttr, isBooleanAttr, isKnownHtmlAttr, includeBooleanAttr, isRenderableAttrValue } from '@vue/shared';\nexport { camelize, capitalize, normalizeClass, normalizeProps, normalizeStyle, toDisplayString, toHandlerKey } from '@vue/shared';\n\nconst stack = [];\nfunction pushWarningContext(vnode) {\n stack.push(vnode);\n}\nfunction popWarningContext() {\n stack.pop();\n}\nfunction warn$1(msg, ...args) {\n pauseTracking();\n const instance = stack.length ? stack[stack.length - 1].component : null;\n const appWarnHandler = instance && instance.appContext.config.warnHandler;\n const trace = getComponentTrace();\n if (appWarnHandler) {\n callWithErrorHandling(\n appWarnHandler,\n instance,\n 11,\n [\n msg + args.join(\"\"),\n instance && instance.proxy,\n trace.map(\n ({ vnode }) => `at <${formatComponentName(instance, vnode.type)}>`\n ).join(\"\\n\"),\n trace\n ]\n );\n } else {\n const warnArgs = [`[Vue warn]: ${msg}`, ...args];\n if (trace.length && // avoid spamming console during tests\n true) {\n warnArgs.push(`\n`, ...formatTrace(trace));\n }\n console.warn(...warnArgs);\n }\n resetTracking();\n}\nfunction getComponentTrace() {\n let currentVNode = stack[stack.length - 1];\n if (!currentVNode) {\n return [];\n }\n const normalizedStack = [];\n while (currentVNode) {\n const last = normalizedStack[0];\n if (last && last.vnode === currentVNode) {\n last.recurseCount++;\n } else {\n normalizedStack.push({\n vnode: currentVNode,\n recurseCount: 0\n });\n }\n const parentInstance = currentVNode.component && currentVNode.component.parent;\n currentVNode = parentInstance && parentInstance.vnode;\n }\n return normalizedStack;\n}\nfunction formatTrace(trace) {\n const logs = [];\n trace.forEach((entry, i) => {\n logs.push(...i === 0 ? [] : [`\n`], ...formatTraceEntry(entry));\n });\n return logs;\n}\nfunction formatTraceEntry({ vnode, recurseCount }) {\n const postfix = recurseCount > 0 ? `... (${recurseCount} recursive calls)` : ``;\n const isRoot = vnode.component ? vnode.component.parent == null : false;\n const open = ` at <${formatComponentName(\n vnode.component,\n vnode.type,\n isRoot\n )}`;\n const close = `>` + postfix;\n return vnode.props ? [open, ...formatProps(vnode.props), close] : [open + close];\n}\nfunction formatProps(props) {\n const res = [];\n const keys = Object.keys(props);\n keys.slice(0, 3).forEach((key) => {\n res.push(...formatProp(key, props[key]));\n });\n if (keys.length > 3) {\n res.push(` ...`);\n }\n return res;\n}\nfunction formatProp(key, value, raw) {\n if (isString(value)) {\n value = JSON.stringify(value);\n return raw ? value : [`${key}=${value}`];\n } else if (typeof value === \"number\" || typeof value === \"boolean\" || value == null) {\n return raw ? value : [`${key}=${value}`];\n } else if (isRef(value)) {\n value = formatProp(key, toRaw(value.value), true);\n return raw ? value : [`${key}=Ref<`, value, `>`];\n } else if (isFunction(value)) {\n return [`${key}=fn${value.name ? `<${value.name}>` : ``}`];\n } else {\n value = toRaw(value);\n return raw ? value : [`${key}=`, value];\n }\n}\nfunction assertNumber(val, type) {\n if (!!!(process.env.NODE_ENV !== \"production\"))\n return;\n if (val === void 0) {\n return;\n } else if (typeof val !== \"number\") {\n warn$1(`${type} is not a valid number - got ${JSON.stringify(val)}.`);\n } else if (isNaN(val)) {\n warn$1(`${type} is NaN - the duration expression might be incorrect.`);\n }\n}\n\nconst ErrorCodes = {\n \"SETUP_FUNCTION\": 0,\n \"0\": \"SETUP_FUNCTION\",\n \"RENDER_FUNCTION\": 1,\n \"1\": \"RENDER_FUNCTION\",\n \"WATCH_GETTER\": 2,\n \"2\": \"WATCH_GETTER\",\n \"WATCH_CALLBACK\": 3,\n \"3\": \"WATCH_CALLBACK\",\n \"WATCH_CLEANUP\": 4,\n \"4\": \"WATCH_CLEANUP\",\n \"NATIVE_EVENT_HANDLER\": 5,\n \"5\": \"NATIVE_EVENT_HANDLER\",\n \"COMPONENT_EVENT_HANDLER\": 6,\n \"6\": \"COMPONENT_EVENT_HANDLER\",\n \"VNODE_HOOK\": 7,\n \"7\": \"VNODE_HOOK\",\n \"DIRECTIVE_HOOK\": 8,\n \"8\": \"DIRECTIVE_HOOK\",\n \"TRANSITION_HOOK\": 9,\n \"9\": \"TRANSITION_HOOK\",\n \"APP_ERROR_HANDLER\": 10,\n \"10\": \"APP_ERROR_HANDLER\",\n \"APP_WARN_HANDLER\": 11,\n \"11\": \"APP_WARN_HANDLER\",\n \"FUNCTION_REF\": 12,\n \"12\": \"FUNCTION_REF\",\n \"ASYNC_COMPONENT_LOADER\": 13,\n \"13\": \"ASYNC_COMPONENT_LOADER\",\n \"SCHEDULER\": 14,\n \"14\": \"SCHEDULER\"\n};\nconst ErrorTypeStrings$1 = {\n [\"sp\"]: \"serverPrefetch hook\",\n [\"bc\"]: \"beforeCreate hook\",\n [\"c\"]: \"created hook\",\n [\"bm\"]: \"beforeMount hook\",\n [\"m\"]: \"mounted hook\",\n [\"bu\"]: \"beforeUpdate hook\",\n [\"u\"]: \"updated\",\n [\"bum\"]: \"beforeUnmount hook\",\n [\"um\"]: \"unmounted hook\",\n [\"a\"]: \"activated hook\",\n [\"da\"]: \"deactivated hook\",\n [\"ec\"]: \"errorCaptured hook\",\n [\"rtc\"]: \"renderTracked hook\",\n [\"rtg\"]: \"renderTriggered hook\",\n [0]: \"setup function\",\n [1]: \"render function\",\n [2]: \"watcher getter\",\n [3]: \"watcher callback\",\n [4]: \"watcher cleanup function\",\n [5]: \"native event handler\",\n [6]: \"component event handler\",\n [7]: \"vnode hook\",\n [8]: \"directive hook\",\n [9]: \"transition hook\",\n [10]: \"app errorHandler\",\n [11]: \"app warnHandler\",\n [12]: \"ref function\",\n [13]: \"async component loader\",\n [14]: \"scheduler flush. This is likely a Vue internals bug. Please open an issue at https://github.com/vuejs/core .\"\n};\nfunction callWithErrorHandling(fn, instance, type, args) {\n let res;\n try {\n res = args ? fn(...args) : fn();\n } catch (err) {\n handleError(err, instance, type);\n }\n return res;\n}\nfunction callWithAsyncErrorHandling(fn, instance, type, args) {\n if (isFunction(fn)) {\n const res = callWithErrorHandling(fn, instance, type, args);\n if (res && isPromise(res)) {\n res.catch((err) => {\n handleError(err, instance, type);\n });\n }\n return res;\n }\n const values = [];\n for (let i = 0; i < fn.length; i++) {\n values.push(callWithAsyncErrorHandling(fn[i], instance, type, args));\n }\n return values;\n}\nfunction handleError(err, instance, type, throwInDev = true) {\n const contextVNode = instance ? instance.vnode : null;\n if (instance) {\n let cur = instance.parent;\n const exposedInstance = instance.proxy;\n const errorInfo = !!(process.env.NODE_ENV !== \"production\") ? ErrorTypeStrings$1[type] : `https://vuejs.org/error-reference/#runtime-${type}`;\n while (cur) {\n const errorCapturedHooks = cur.ec;\n if (errorCapturedHooks) {\n for (let i = 0; i < errorCapturedHooks.length; i++) {\n if (errorCapturedHooks[i](err, exposedInstance, errorInfo) === false) {\n return;\n }\n }\n }\n cur = cur.parent;\n }\n const appErrorHandler = instance.appContext.config.errorHandler;\n if (appErrorHandler) {\n callWithErrorHandling(\n appErrorHandler,\n null,\n 10,\n [err, exposedInstance, errorInfo]\n );\n return;\n }\n }\n logError(err, type, contextVNode, throwInDev);\n}\nfunction logError(err, type, contextVNode, throwInDev = true) {\n if (!!(process.env.NODE_ENV !== \"production\")) {\n const info = ErrorTypeStrings$1[type];\n if (contextVNode) {\n pushWarningContext(contextVNode);\n }\n warn$1(`Unhandled error${info ? ` during execution of ${info}` : ``}`);\n if (contextVNode) {\n popWarningContext();\n }\n if (throwInDev) {\n throw err;\n } else {\n console.error(err);\n }\n } else {\n console.error(err);\n }\n}\n\nlet isFlushing = false;\nlet isFlushPending = false;\nconst queue = [];\nlet flushIndex = 0;\nconst pendingPostFlushCbs = [];\nlet activePostFlushCbs = null;\nlet postFlushIndex = 0;\nconst resolvedPromise = /* @__PURE__ */ Promise.resolve();\nlet currentFlushPromise = null;\nconst RECURSION_LIMIT = 100;\nfunction nextTick(fn) {\n const p = currentFlushPromise || resolvedPromise;\n return fn ? p.then(this ? fn.bind(this) : fn) : p;\n}\nfunction findInsertionIndex(id) {\n let start = flushIndex + 1;\n let end = queue.length;\n while (start < end) {\n const middle = start + end >>> 1;\n const middleJob = queue[middle];\n const middleJobId = getId(middleJob);\n if (middleJobId < id || middleJobId === id && middleJob.pre) {\n start = middle + 1;\n } else {\n end = middle;\n }\n }\n return start;\n}\nfunction queueJob(job) {\n if (!queue.length || !queue.includes(\n job,\n isFlushing && job.allowRecurse ? flushIndex + 1 : flushIndex\n )) {\n if (job.id == null) {\n queue.push(job);\n } else {\n queue.splice(findInsertionIndex(job.id), 0, job);\n }\n queueFlush();\n }\n}\nfunction queueFlush() {\n if (!isFlushing && !isFlushPending) {\n isFlushPending = true;\n currentFlushPromise = resolvedPromise.then(flushJobs);\n }\n}\nfunction invalidateJob(job) {\n const i = queue.indexOf(job);\n if (i > flushIndex) {\n queue.splice(i, 1);\n }\n}\nfunction queuePostFlushCb(cb) {\n if (!isArray(cb)) {\n if (!activePostFlushCbs || !activePostFlushCbs.includes(\n cb,\n cb.allowRecurse ? postFlushIndex + 1 : postFlushIndex\n )) {\n pendingPostFlushCbs.push(cb);\n }\n } else {\n pendingPostFlushCbs.push(...cb);\n }\n queueFlush();\n}\nfunction flushPreFlushCbs(instance, seen, i = isFlushing ? flushIndex + 1 : 0) {\n if (!!(process.env.NODE_ENV !== \"production\")) {\n seen = seen || /* @__PURE__ */ new Map();\n }\n for (; i < queue.length; i++) {\n const cb = queue[i];\n if (cb && cb.pre) {\n if (instance && cb.id !== instance.uid) {\n continue;\n }\n if (!!(process.env.NODE_ENV !== \"production\") && checkRecursiveUpdates(seen, cb)) {\n continue;\n }\n queue.splice(i, 1);\n i--;\n cb();\n }\n }\n}\nfunction flushPostFlushCbs(seen) {\n if (pendingPostFlushCbs.length) {\n const deduped = [...new Set(pendingPostFlushCbs)].sort(\n (a, b) => getId(a) - getId(b)\n );\n pendingPostFlushCbs.length = 0;\n if (activePostFlushCbs) {\n activePostFlushCbs.push(...deduped);\n return;\n }\n activePostFlushCbs = deduped;\n if (!!(process.env.NODE_ENV !== \"production\")) {\n seen = seen || /* @__PURE__ */ new Map();\n }\n for (postFlushIndex = 0; postFlushIndex < activePostFlushCbs.length; postFlushIndex++) {\n if (!!(process.env.NODE_ENV !== \"production\") && checkRecursiveUpdates(seen, activePostFlushCbs[postFlushIndex])) {\n continue;\n }\n activePostFlushCbs[postFlushIndex]();\n }\n activePostFlushCbs = null;\n postFlushIndex = 0;\n }\n}\nconst getId = (job) => job.id == null ? Infinity : job.id;\nconst comparator = (a, b) => {\n const diff = getId(a) - getId(b);\n if (diff === 0) {\n if (a.pre && !b.pre)\n return -1;\n if (b.pre && !a.pre)\n return 1;\n }\n return diff;\n};\nfunction flushJobs(seen) {\n isFlushPending = false;\n isFlushing = true;\n if (!!(process.env.NODE_ENV !== \"production\")) {\n seen = seen || /* @__PURE__ */ new Map();\n }\n queue.sort(comparator);\n const check = !!(process.env.NODE_ENV !== \"production\") ? (job) => checkRecursiveUpdates(seen, job) : NOOP;\n try {\n for (flushIndex = 0; flushIndex < queue.length; flushIndex++) {\n const job = queue[flushIndex];\n if (job && job.active !== false) {\n if (!!(process.env.NODE_ENV !== \"production\") && check(job)) {\n continue;\n }\n callWithErrorHandling(job, null, 14);\n }\n }\n } finally {\n flushIndex = 0;\n queue.length = 0;\n flushPostFlushCbs(seen);\n isFlushing = false;\n currentFlushPromise = null;\n if (queue.length || pendingPostFlushCbs.length) {\n flushJobs(seen);\n }\n }\n}\nfunction checkRecursiveUpdates(seen, fn) {\n if (!seen.has(fn)) {\n seen.set(fn, 1);\n } else {\n const count = seen.get(fn);\n if (count > RECURSION_LIMIT) {\n const instance = fn.ownerInstance;\n const componentName = instance && getComponentName(instance.type);\n handleError(\n `Maximum recursive updates exceeded${componentName ? ` in component <${componentName}>` : ``}. This means you have a reactive effect that is mutating its own dependencies and thus recursively triggering itself. Possible sources include component template, render function, updated hook or watcher source function.`,\n null,\n 10\n );\n return true;\n } else {\n seen.set(fn, count + 1);\n }\n }\n}\n\nlet isHmrUpdating = false;\nconst hmrDirtyComponents = /* @__PURE__ */ new Set();\nif (!!(process.env.NODE_ENV !== \"production\")) {\n getGlobalThis().__VUE_HMR_RUNTIME__ = {\n createRecord: tryWrap(createRecord),\n rerender: tryWrap(rerender),\n reload: tryWrap(reload)\n };\n}\nconst map = /* @__PURE__ */ new Map();\nfunction registerHMR(instance) {\n const id = instance.type.__hmrId;\n let record = map.get(id);\n if (!record) {\n createRecord(id, instance.type);\n record = map.get(id);\n }\n record.instances.add(instance);\n}\nfunction unregisterHMR(instance) {\n map.get(instance.type.__hmrId).instances.delete(instance);\n}\nfunction createRecord(id, initialDef) {\n if (map.has(id)) {\n return false;\n }\n map.set(id, {\n initialDef: normalizeClassComponent(initialDef),\n instances: /* @__PURE__ */ new Set()\n });\n return true;\n}\nfunction normalizeClassComponent(component) {\n return isClassComponent(component) ? component.__vccOpts : component;\n}\nfunction rerender(id, newRender) {\n const record = map.get(id);\n if (!record) {\n return;\n }\n record.initialDef.render = newRender;\n [...record.instances].forEach((instance) => {\n if (newRender) {\n instance.render = newRender;\n normalizeClassComponent(instance.type).render = newRender;\n }\n instance.renderCache = [];\n isHmrUpdating = true;\n instance.effect.dirty = true;\n instance.update();\n isHmrUpdating = false;\n });\n}\nfunction reload(id, newComp) {\n const record = map.get(id);\n if (!record)\n return;\n newComp = normalizeClassComponent(newComp);\n updateComponentDef(record.initialDef, newComp);\n const instances = [...record.instances];\n for (const instance of instances) {\n const oldComp = normalizeClassComponent(instance.type);\n if (!hmrDirtyComponents.has(oldComp)) {\n if (oldComp !== record.initialDef) {\n updateComponentDef(oldComp, newComp);\n }\n hmrDirtyComponents.add(oldComp);\n }\n instance.appContext.propsCache.delete(instance.type);\n instance.appContext.emitsCache.delete(instance.type);\n instance.appContext.optionsCache.delete(instance.type);\n if (instance.ceReload) {\n hmrDirtyComponents.add(oldComp);\n instance.ceReload(newComp.styles);\n hmrDirtyComponents.delete(oldComp);\n } else if (instance.parent) {\n instance.parent.effect.dirty = true;\n queueJob(instance.parent.update);\n } else if (instance.appContext.reload) {\n instance.appContext.reload();\n } else if (typeof window !== \"undefined\") {\n window.location.reload();\n } else {\n console.warn(\n \"[HMR] Root or manually mounted instance modified. Full reload required.\"\n );\n }\n }\n queuePostFlushCb(() => {\n for (const instance of instances) {\n hmrDirtyComponents.delete(\n normalizeClassComponent(instance.type)\n );\n }\n });\n}\nfunction updateComponentDef(oldComp, newComp) {\n extend(oldComp, newComp);\n for (const key in oldComp) {\n if (key !== \"__file\" && !(key in newComp)) {\n delete oldComp[key];\n }\n }\n}\nfunction tryWrap(fn) {\n return (id, arg) => {\n try {\n return fn(id, arg);\n } catch (e) {\n console.error(e);\n console.warn(\n `[HMR] Something went wrong during Vue component hot-reload. Full reload required.`\n );\n }\n };\n}\n\nlet devtools$1;\nlet buffer = [];\nlet devtoolsNotInstalled = false;\nfunction emit$1(event, ...args) {\n if (devtools$1) {\n devtools$1.emit(event, ...args);\n } else if (!devtoolsNotInstalled) {\n buffer.push({ event, args });\n }\n}\nfunction setDevtoolsHook$1(hook, target) {\n var _a, _b;\n devtools$1 = hook;\n if (devtools$1) {\n devtools$1.enabled = true;\n buffer.forEach(({ event, args }) => devtools$1.emit(event, ...args));\n buffer = [];\n } else if (\n // handle late devtools injection - only do this if we are in an actual\n // browser environment to avoid the timer handle stalling test runner exit\n // (#4815)\n typeof window !== \"undefined\" && // some envs mock window but not fully\n window.HTMLElement && // also exclude jsdom\n !((_b = (_a = window.navigator) == null ? void 0 : _a.userAgent) == null ? void 0 : _b.includes(\"jsdom\"))\n ) {\n const replay = target.__VUE_DEVTOOLS_HOOK_REPLAY__ = target.__VUE_DEVTOOLS_HOOK_REPLAY__ || [];\n replay.push((newHook) => {\n setDevtoolsHook$1(newHook, target);\n });\n setTimeout(() => {\n if (!devtools$1) {\n target.__VUE_DEVTOOLS_HOOK_REPLAY__ = null;\n devtoolsNotInstalled = true;\n buffer = [];\n }\n }, 3e3);\n } else {\n devtoolsNotInstalled = true;\n buffer = [];\n }\n}\nfunction devtoolsInitApp(app, version) {\n emit$1(\"app:init\" /* APP_INIT */, app, version, {\n Fragment,\n Text,\n Comment,\n Static\n });\n}\nfunction devtoolsUnmountApp(app) {\n emit$1(\"app:unmount\" /* APP_UNMOUNT */, app);\n}\nconst devtoolsComponentAdded = /* @__PURE__ */ createDevtoolsComponentHook(\n \"component:added\" /* COMPONENT_ADDED */\n);\nconst devtoolsComponentUpdated = /* @__PURE__ */ createDevtoolsComponentHook(\"component:updated\" /* COMPONENT_UPDATED */);\nconst _devtoolsComponentRemoved = /* @__PURE__ */ createDevtoolsComponentHook(\n \"component:removed\" /* COMPONENT_REMOVED */\n);\nconst devtoolsComponentRemoved = (component) => {\n if (devtools$1 && typeof devtools$1.cleanupBuffer === \"function\" && // remove the component if it wasn't buffered\n !devtools$1.cleanupBuffer(component)) {\n _devtoolsComponentRemoved(component);\n }\n};\nfunction createDevtoolsComponentHook(hook) {\n return (component) => {\n emit$1(\n hook,\n component.appContext.app,\n component.uid,\n component.parent ? component.parent.uid : void 0,\n component\n );\n };\n}\nconst devtoolsPerfStart = /* @__PURE__ */ createDevtoolsPerformanceHook(\n \"perf:start\" /* PERFORMANCE_START */\n);\nconst devtoolsPerfEnd = /* @__PURE__ */ createDevtoolsPerformanceHook(\n \"perf:end\" /* PERFORMANCE_END */\n);\nfunction createDevtoolsPerformanceHook(hook) {\n return (component, type, time) => {\n emit$1(hook, component.appContext.app, component.uid, component, type, time);\n };\n}\nfunction devtoolsComponentEmit(component, event, params) {\n emit$1(\n \"component:emit\" /* COMPONENT_EMIT */,\n component.appContext.app,\n component,\n event,\n params\n );\n}\n\nfunction emit(instance, event, ...rawArgs) {\n if (instance.isUnmounted)\n return;\n const props = instance.vnode.props || EMPTY_OBJ;\n if (!!(process.env.NODE_ENV !== \"production\")) {\n const {\n emitsOptions,\n propsOptions: [propsOptions]\n } = instance;\n if (emitsOptions) {\n if (!(event in emitsOptions) && true) {\n if (!propsOptions || !(toHandlerKey(event) in propsOptions)) {\n warn$1(\n `Component emitted event \"${event}\" but it is neither declared in the emits option nor as an \"${toHandlerKey(event)}\" prop.`\n );\n }\n } else {\n const validator = emitsOptions[event];\n if (isFunction(validator)) {\n const isValid = validator(...rawArgs);\n if (!isValid) {\n warn$1(\n `Invalid event arguments: event validation failed for event \"${event}\".`\n );\n }\n }\n }\n }\n }\n let args = rawArgs;\n const isModelListener = event.startsWith(\"update:\");\n const modelArg = isModelListener && event.slice(7);\n if (modelArg && modelArg in props) {\n const modifiersKey = `${modelArg === \"modelValue\" ? \"model\" : modelArg}Modifiers`;\n const { number, trim } = props[modifiersKey] || EMPTY_OBJ;\n if (trim) {\n args = rawArgs.map((a) => isString(a) ? a.trim() : a);\n }\n if (number) {\n args = rawArgs.map(looseToNumber);\n }\n }\n if (!!(process.env.NODE_ENV !== \"production\") || __VUE_PROD_DEVTOOLS__) {\n devtoolsComponentEmit(instance, event, args);\n }\n if (!!(process.env.NODE_ENV !== \"production\")) {\n const lowerCaseEvent = event.toLowerCase();\n if (lowerCaseEvent !== event && props[toHandlerKey(lowerCaseEvent)]) {\n warn$1(\n `Event \"${lowerCaseEvent}\" is emitted in component ${formatComponentName(\n instance,\n instance.type\n )} but the handler is registered for \"${event}\". Note that HTML attributes are case-insensitive and you cannot use v-on to listen to camelCase events when using in-DOM templates. You should probably use \"${hyphenate(\n event\n )}\" instead of \"${event}\".`\n );\n }\n }\n let handlerName;\n let handler = props[handlerName = toHandlerKey(event)] || // also try camelCase event handler (#2249)\n props[handlerName = toHandlerKey(camelize(event))];\n if (!handler && isModelListener) {\n handler = props[handlerName = toHandlerKey(hyphenate(event))];\n }\n if (handler) {\n callWithAsyncErrorHandling(\n handler,\n instance,\n 6,\n args\n );\n }\n const onceHandler = props[handlerName + `Once`];\n if (onceHandler) {\n if (!instance.emitted) {\n instance.emitted = {};\n } else if (instance.emitted[handlerName]) {\n return;\n }\n instance.emitted[handlerName] = true;\n callWithAsyncErrorHandling(\n onceHandler,\n instance,\n 6,\n args\n );\n }\n}\nfunction normalizeEmitsOptions(comp, appContext, asMixin = false) {\n const cache = appContext.emitsCache;\n const cached = cache.get(comp);\n if (cached !== void 0) {\n return cached;\n }\n const raw = comp.emits;\n let normalized = {};\n let hasExtends = false;\n if (__VUE_OPTIONS_API__ && !isFunction(comp)) {\n const extendEmits = (raw2) => {\n const normalizedFromExtend = normalizeEmitsOptions(raw2, appContext, true);\n if (normalizedFromExtend) {\n hasExtends = true;\n extend(normalized, normalizedFromExtend);\n }\n };\n if (!asMixin && appContext.mixins.length) {\n appContext.mixins.forEach(extendEmits);\n }\n if (comp.extends) {\n extendEmits(comp.extends);\n }\n if (comp.mixins) {\n comp.mixins.forEach(extendEmits);\n }\n }\n if (!raw && !hasExtends) {\n if (isObject(comp)) {\n cache.set(comp, null);\n }\n return null;\n }\n if (isArray(raw)) {\n raw.forEach((key) => normalized[key] = null);\n } else {\n extend(normalized, raw);\n }\n if (isObject(comp)) {\n cache.set(comp, normalized);\n }\n return normalized;\n}\nfunction isEmitListener(options, key) {\n if (!options || !isOn(key)) {\n return false;\n }\n key = key.slice(2).replace(/Once$/, \"\");\n return hasOwn(options, key[0].toLowerCase() + key.slice(1)) || hasOwn(options, hyphenate(key)) || hasOwn(options, key);\n}\n\nlet currentRenderingInstance = null;\nlet currentScopeId = null;\nfunction setCurrentRenderingInstance(instance) {\n const prev = currentRenderingInstance;\n currentRenderingInstance = instance;\n currentScopeId = instance && instance.type.__scopeId || null;\n return prev;\n}\nfunction pushScopeId(id) {\n currentScopeId = id;\n}\nfunction popScopeId() {\n currentScopeId = null;\n}\nconst withScopeId = (_id) => withCtx;\nfunction withCtx(fn, ctx = currentRenderingInstance, isNonScopedSlot) {\n if (!ctx)\n return fn;\n if (fn._n) {\n return fn;\n }\n const renderFnWithContext = (...args) => {\n if (renderFnWithContext._d) {\n setBlockTracking(-1);\n }\n const prevInstance = setCurrentRenderingInstance(ctx);\n let res;\n try {\n res = fn(...args);\n } finally {\n setCurrentRenderingInstance(prevInstance);\n if (renderFnWithContext._d) {\n setBlockTracking(1);\n }\n }\n if (!!(process.env.NODE_ENV !== \"production\") || __VUE_PROD_DEVTOOLS__) {\n devtoolsComponentUpdated(ctx);\n }\n return res;\n };\n renderFnWithContext._n = true;\n renderFnWithContext._c = true;\n renderFnWithContext._d = true;\n return renderFnWithContext;\n}\n\nlet accessedAttrs = false;\nfunction markAttrsAccessed() {\n accessedAttrs = true;\n}\nfunction renderComponentRoot(instance) {\n const {\n type: Component,\n vnode,\n proxy,\n withProxy,\n props,\n propsOptions: [propsOptions],\n slots,\n attrs,\n emit,\n render,\n renderCache,\n data,\n setupState,\n ctx,\n inheritAttrs\n } = instance;\n let result;\n let fallthroughAttrs;\n const prev = setCurrentRenderingInstance(instance);\n if (!!(process.env.NODE_ENV !== \"production\")) {\n accessedAttrs = false;\n }\n try {\n if (vnode.shapeFlag & 4) {\n const proxyToUse = withProxy || proxy;\n const thisProxy = !!(process.env.NODE_ENV !== \"production\") && setupState.__isScriptSetup ? new Proxy(proxyToUse, {\n get(target, key, receiver) {\n warn$1(\n `Property '${String(\n key\n )}' was accessed via 'this'. Avoid using 'this' in templates.`\n );\n return Reflect.get(target, key, receiver);\n }\n }) : proxyToUse;\n result = normalizeVNode(\n render.call(\n thisProxy,\n proxyToUse,\n renderCache,\n props,\n setupState,\n data,\n ctx\n )\n );\n fallthroughAttrs = attrs;\n } else {\n const render2 = Component;\n if (!!(process.env.NODE_ENV !== \"production\") && attrs === props) {\n markAttrsAccessed();\n }\n result = normalizeVNode(\n render2.length > 1 ? render2(\n props,\n !!(process.env.NODE_ENV !== \"production\") ? {\n get attrs() {\n markAttrsAccessed();\n return attrs;\n },\n slots,\n emit\n } : { attrs, slots, emit }\n ) : render2(\n props,\n null\n /* we know it doesn't need it */\n )\n );\n fallthroughAttrs = Component.props ? attrs : getFunctionalFallthrough(attrs);\n }\n } catch (err) {\n blockStack.length = 0;\n handleError(err, instance, 1);\n result = createVNode(Comment);\n }\n let root = result;\n let setRoot = void 0;\n if (!!(process.env.NODE_ENV !== \"production\") && result.patchFlag > 0 && result.patchFlag & 2048) {\n [root, setRoot] = getChildRoot(result);\n }\n if (fallthroughAttrs && inheritAttrs !== false) {\n const keys = Object.keys(fallthroughAttrs);\n const { shapeFlag } = root;\n if (keys.length) {\n if (shapeFlag & (1 | 6)) {\n if (propsOptions && keys.some(isModelListener)) {\n fallthroughAttrs = filterModelListeners(\n fallthroughAttrs,\n propsOptions\n );\n }\n root = cloneVNode(root, fallthroughAttrs);\n } else if (!!(process.env.NODE_ENV !== \"production\") && !accessedAttrs && root.type !== Comment) {\n const allAttrs = Object.keys(attrs);\n const eventAttrs = [];\n const extraAttrs = [];\n for (let i = 0, l = allAttrs.length; i < l; i++) {\n const key = allAttrs[i];\n if (isOn(key)) {\n if (!isModelListener(key)) {\n eventAttrs.push(key[2].toLowerCase() + key.slice(3));\n }\n } else {\n extraAttrs.push(key);\n }\n }\n if (extraAttrs.length) {\n warn$1(\n `Extraneous non-props attributes (${extraAttrs.join(\", \")}) were passed to component but could not be automatically inherited because component renders fragment or text root nodes.`\n );\n }\n if (eventAttrs.length) {\n warn$1(\n `Extraneous non-emits event listeners (${eventAttrs.join(\", \")}) were passed to component but could not be automatically inherited because component renders fragment or text root nodes. If the listener is intended to be a component custom event listener only, declare it using the \"emits\" option.`\n );\n }\n }\n }\n }\n if (vnode.dirs) {\n if (!!(process.env.NODE_ENV !== \"production\") && !isElementRoot(root)) {\n warn$1(\n `Runtime directive used on component with non-element root node. The directives will not function as intended.`\n );\n }\n root = cloneVNode(root);\n root.dirs = root.dirs ? root.dirs.concat(vnode.dirs) : vnode.dirs;\n }\n if (vnode.transition) {\n if (!!(process.env.NODE_ENV !== \"production\") && !isElementRoot(root)) {\n warn$1(\n `Component inside renders non-element root node that cannot be animated.`\n );\n }\n root.transition = vnode.transition;\n }\n if (!!(process.env.NODE_ENV !== \"production\") && setRoot) {\n setRoot(root);\n } else {\n result = root;\n }\n setCurrentRenderingInstance(prev);\n return result;\n}\nconst getChildRoot = (vnode) => {\n const rawChildren = vnode.children;\n const dynamicChildren = vnode.dynamicChildren;\n const childRoot = filterSingleRoot(rawChildren, false);\n if (!childRoot) {\n return [vnode, void 0];\n } else if (!!(process.env.NODE_ENV !== \"production\") && childRoot.patchFlag > 0 && childRoot.patchFlag & 2048) {\n return getChildRoot(childRoot);\n }\n const index = rawChildren.indexOf(childRoot);\n const dynamicIndex = dynamicChildren ? dynamicChildren.indexOf(childRoot) : -1;\n const setRoot = (updatedRoot) => {\n rawChildren[index] = updatedRoot;\n if (dynamicChildren) {\n if (dynamicIndex > -1) {\n dynamicChildren[dynamicIndex] = updatedRoot;\n } else if (updatedRoot.patchFlag > 0) {\n vnode.dynamicChildren = [...dynamicChildren, updatedRoot];\n }\n }\n };\n return [normalizeVNode(childRoot), setRoot];\n};\nfunction filterSingleRoot(children, recurse = true) {\n let singleRoot;\n for (let i = 0; i < children.length; i++) {\n const child = children[i];\n if (isVNode(child)) {\n if (child.type !== Comment || child.children === \"v-if\") {\n if (singleRoot) {\n return;\n } else {\n singleRoot = child;\n if (!!(process.env.NODE_ENV !== \"production\") && recurse && singleRoot.patchFlag > 0 && singleRoot.patchFlag & 2048) {\n return filterSingleRoot(singleRoot.children);\n }\n }\n }\n } else {\n return;\n }\n }\n return singleRoot;\n}\nconst getFunctionalFallthrough = (attrs) => {\n let res;\n for (const key in attrs) {\n if (key === \"class\" || key === \"style\" || isOn(key)) {\n (res || (res = {}))[key] = attrs[key];\n }\n }\n return res;\n};\nconst filterModelListeners = (attrs, props) => {\n const res = {};\n for (const key in attrs) {\n if (!isModelListener(key) || !(key.slice(9) in props)) {\n res[key] = attrs[key];\n }\n }\n return res;\n};\nconst isElementRoot = (vnode) => {\n return vnode.shapeFlag & (6 | 1) || vnode.type === Comment;\n};\nfunction shouldUpdateComponent(prevVNode, nextVNode, optimized) {\n const { props: prevProps, children: prevChildren, component } = prevVNode;\n const { props: nextProps, children: nextChildren, patchFlag } = nextVNode;\n const emits = component.emitsOptions;\n if (!!(process.env.NODE_ENV !== \"production\") && (prevChildren || nextChildren) && isHmrUpdating) {\n return true;\n }\n if (nextVNode.dirs || nextVNode.transition) {\n return true;\n }\n if (optimized && patchFlag >= 0) {\n if (patchFlag & 1024) {\n return true;\n }\n if (patchFlag & 16) {\n if (!prevProps) {\n return !!nextProps;\n }\n return hasPropsChanged(prevProps, nextProps, emits);\n } else if (patchFlag & 8) {\n const dynamicProps = nextVNode.dynamicProps;\n for (let i = 0; i < dynamicProps.length; i++) {\n const key = dynamicProps[i];\n if (nextProps[key] !== prevProps[key] && !isEmitListener(emits, key)) {\n return true;\n }\n }\n }\n } else {\n if (prevChildren || nextChildren) {\n if (!nextChildren || !nextChildren.$stable) {\n return true;\n }\n }\n if (prevProps === nextProps) {\n return false;\n }\n if (!prevProps) {\n return !!nextProps;\n }\n if (!nextProps) {\n return true;\n }\n return hasPropsChanged(prevProps, nextProps, emits);\n }\n return false;\n}\nfunction hasPropsChanged(prevProps, nextProps, emitsOptions) {\n const nextKeys = Object.keys(nextProps);\n if (nextKeys.length !== Object.keys(prevProps).length) {\n return true;\n }\n for (let i = 0; i < nextKeys.length; i++) {\n const key = nextKeys[i];\n if (nextProps[key] !== prevProps[key] && !isEmitListener(emitsOptions, key)) {\n return true;\n }\n }\n return false;\n}\nfunction updateHOCHostEl({ vnode, parent }, el) {\n while (parent) {\n const root = parent.subTree;\n if (root.suspense && root.suspense.activeBranch === vnode) {\n root.el = vnode.el;\n }\n if (root === vnode) {\n (vnode = parent.vnode).el = el;\n parent = parent.parent;\n } else {\n break;\n }\n }\n}\n\nconst COMPONENTS = \"components\";\nconst DIRECTIVES = \"directives\";\nfunction resolveComponent(name, maybeSelfReference) {\n return resolveAsset(COMPONENTS, name, true, maybeSelfReference) || name;\n}\nconst NULL_DYNAMIC_COMPONENT = Symbol.for(\"v-ndc\");\nfunction resolveDynamicComponent(component) {\n if (isString(component)) {\n return resolveAsset(COMPONENTS, component, false) || component;\n } else {\n return component || NULL_DYNAMIC_COMPONENT;\n }\n}\nfunction resolveDirective(name) {\n return resolveAsset(DIRECTIVES, name);\n}\nfunction resolveAsset(type, name, warnMissing = true, maybeSelfReference = false) {\n const instance = currentRenderingInstance || currentInstance;\n if (instance) {\n const Component = instance.type;\n if (type === COMPONENTS) {\n const selfName = getComponentName(\n Component,\n false\n );\n if (selfName && (selfName === name || selfName === camelize(name) || selfName === capitalize(camelize(name)))) {\n return Component;\n }\n }\n const res = (\n // local registration\n // check instance[type] first which is resolved for options API\n resolve(instance[type] || Component[type], name) || // global registration\n resolve(instance.appContext[type], name)\n );\n if (!res && maybeSelfReference) {\n return Component;\n }\n if (!!(process.env.NODE_ENV !== \"production\") && warnMissing && !res) {\n const extra = type === COMPONENTS ? `\nIf this is a native custom element, make sure to exclude it from component resolution via compilerOptions.isCustomElement.` : ``;\n warn$1(`Failed to resolve ${type.slice(0, -1)}: ${name}${extra}`);\n }\n return res;\n } else if (!!(process.env.NODE_ENV !== \"production\")) {\n warn$1(\n `resolve${capitalize(type.slice(0, -1))} can only be used in render() or setup().`\n );\n }\n}\nfunction resolve(registry, name) {\n return registry && (registry[name] || registry[camelize(name)] || registry[capitalize(camelize(name))]);\n}\n\nconst isSuspense = (type) => type.__isSuspense;\nlet suspenseId = 0;\nconst SuspenseImpl = {\n name: \"Suspense\",\n // In order to make Suspense tree-shakable, we need to avoid importing it\n // directly in the renderer. The renderer checks for the __isSuspense flag\n // on a vnode's type and calls the `process` method, passing in renderer\n // internals.\n __isSuspense: true,\n process(n1, n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, rendererInternals) {\n if (n1 == null) {\n mountSuspense(\n n2,\n container,\n anchor,\n parentComponent,\n parentSuspense,\n namespace,\n slotScopeIds,\n optimized,\n rendererInternals\n );\n } else {\n if (parentSuspense && parentSuspense.deps > 0) {\n n2.suspense = n1.suspense;\n return;\n }\n patchSuspense(\n n1,\n n2,\n container,\n anchor,\n parentComponent,\n namespace,\n slotScopeIds,\n optimized,\n rendererInternals\n );\n }\n },\n hydrate: hydrateSuspense,\n create: createSuspenseBoundary,\n normalize: normalizeSuspenseChildren\n};\nconst Suspense = SuspenseImpl ;\nfunction triggerEvent(vnode, name) {\n const eventListener = vnode.props && vnode.props[name];\n if (isFunction(eventListener)) {\n eventListener();\n }\n}\nfunction mountSuspense(vnode, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, rendererInternals) {\n const {\n p: patch,\n o: { createElement }\n } = rendererInternals;\n const hiddenContainer = createElement(\"div\");\n const suspense = vnode.suspense = createSuspenseBoundary(\n vnode,\n parentSuspense,\n parentComponent,\n container,\n hiddenContainer,\n anchor,\n namespace,\n slotScopeIds,\n optimized,\n rendererInternals\n );\n patch(\n null,\n suspense.pendingBranch = vnode.ssContent,\n hiddenContainer,\n null,\n parentComponent,\n suspense,\n namespace,\n slotScopeIds\n );\n if (suspense.deps > 0) {\n triggerEvent(vnode, \"onPending\");\n triggerEvent(vnode, \"onFallback\");\n patch(\n null,\n vnode.ssFallback,\n container,\n anchor,\n parentComponent,\n null,\n // fallback tree will not have suspense context\n namespace,\n slotScopeIds\n );\n setActiveBranch(suspense, vnode.ssFallback);\n } else {\n suspense.resolve(false, true);\n }\n}\nfunction patchSuspense(n1, n2, container, anchor, parentComponent, namespace, slotScopeIds, optimized, { p: patch, um: unmount, o: { createElement } }) {\n const suspense = n2.suspense = n1.suspense;\n suspense.vnode = n2;\n n2.el = n1.el;\n const newBranch = n2.ssContent;\n const newFallback = n2.ssFallback;\n const { activeBranch, pendingBranch, isInFallback, isHydrating } = suspense;\n if (pendingBranch) {\n suspense.pendingBranch = newBranch;\n if (isSameVNodeType(newBranch, pendingBranch)) {\n patch(\n pendingBranch,\n newBranch,\n suspense.hiddenContainer,\n null,\n parentComponent,\n suspense,\n namespace,\n slotScopeIds,\n optimized\n );\n if (suspense.deps <= 0) {\n suspense.resolve();\n } else if (isInFallback) {\n if (!isHydrating) {\n patch(\n activeBranch,\n newFallback,\n container,\n anchor,\n parentComponent,\n null,\n // fallback tree will not have suspense context\n namespace,\n slotScopeIds,\n optimized\n );\n setActiveBranch(suspense, newFallback);\n }\n }\n } else {\n suspense.pendingId = suspenseId++;\n if (isHydrating) {\n suspense.isHydrating = false;\n suspense.activeBranch = pendingBranch;\n } else {\n unmount(pendingBranch, parentComponent, suspense);\n }\n suspense.deps = 0;\n suspense.effects.length = 0;\n suspense.hiddenContainer = createElement(\"div\");\n if (isInFallback) {\n patch(\n null,\n newBranch,\n suspense.hiddenContainer,\n null,\n parentComponent,\n suspense,\n namespace,\n slotScopeIds,\n optimized\n );\n if (suspense.deps <= 0) {\n suspense.resolve();\n } else {\n patch(\n activeBranch,\n newFallback,\n container,\n anchor,\n parentComponent,\n null,\n // fallback tree will not have suspense context\n namespace,\n slotScopeIds,\n optimized\n );\n setActiveBranch(suspense, newFallback);\n }\n } else if (activeBranch && isSameVNodeType(newBranch, activeBranch)) {\n patch(\n activeBranch,\n newBranch,\n container,\n anchor,\n parentComponent,\n suspense,\n namespace,\n slotScopeIds,\n optimized\n );\n suspense.resolve(true);\n } else {\n patch(\n null,\n newBranch,\n suspense.hiddenContainer,\n null,\n parentComponent,\n suspense,\n namespace,\n slotScopeIds,\n optimized\n );\n if (suspense.deps <= 0) {\n suspense.resolve();\n }\n }\n }\n } else {\n if (activeBranch && isSameVNodeType(newBranch, activeBranch)) {\n patch(\n activeBranch,\n newBranch,\n container,\n anchor,\n parentComponent,\n suspense,\n namespace,\n slotScopeIds,\n optimized\n );\n setActiveBranch(suspense, newBranch);\n } else {\n triggerEvent(n2, \"onPending\");\n suspense.pendingBranch = newBranch;\n if (newBranch.shapeFlag & 512) {\n suspense.pendingId = newBranch.component.suspenseId;\n } else {\n suspense.pendingId = suspenseId++;\n }\n patch(\n null,\n newBranch,\n suspense.hiddenContainer,\n null,\n parentComponent,\n suspense,\n namespace,\n slotScopeIds,\n optimized\n );\n if (suspense.deps <= 0) {\n suspense.resolve();\n } else {\n const { timeout, pendingId } = suspense;\n if (timeout > 0) {\n setTimeout(() => {\n if (suspense.pendingId === pendingId) {\n suspense.fallback(newFallback);\n }\n }, timeout);\n } else if (timeout === 0) {\n suspense.fallback(newFallback);\n }\n }\n }\n }\n}\nlet hasWarned = false;\nfunction createSuspenseBoundary(vnode, parentSuspense, parentComponent, container, hiddenContainer, anchor, namespace, slotScopeIds, optimized, rendererInternals, isHydrating = false) {\n if (!!(process.env.NODE_ENV !== \"production\") && true && !hasWarned) {\n hasWarned = true;\n console[console.info ? \"info\" : \"log\"](\n ` is an experimental feature and its API will likely change.`\n );\n }\n const {\n p: patch,\n m: move,\n um: unmount,\n n: next,\n o: { parentNode, remove }\n } = rendererInternals;\n let parentSuspenseId;\n const isSuspensible = isVNodeSuspensible(vnode);\n if (isSuspensible) {\n if (parentSuspense == null ? void 0 : parentSuspense.pendingBranch) {\n parentSuspenseId = parentSuspense.pendingId;\n parentSuspense.deps++;\n }\n }\n const timeout = vnode.props ? toNumber(vnode.props.timeout) : void 0;\n if (!!(process.env.NODE_ENV !== \"production\")) {\n assertNumber(timeout, `Suspense timeout`);\n }\n const initialAnchor = anchor;\n const suspense = {\n vnode,\n parent: parentSuspense,\n parentComponent,\n namespace,\n container,\n hiddenContainer,\n deps: 0,\n pendingId: suspenseId++,\n timeout: typeof timeout === \"number\" ? timeout : -1,\n activeBranch: null,\n pendingBranch: null,\n isInFallback: !isHydrating,\n isHydrating,\n isUnmounted: false,\n effects: [],\n resolve(resume = false, sync = false) {\n if (!!(process.env.NODE_ENV !== \"production\")) {\n if (!resume && !suspense.pendingBranch) {\n throw new Error(\n `suspense.resolve() is called without a pending branch.`\n );\n }\n if (suspense.isUnmounted) {\n throw new Error(\n `suspense.resolve() is called on an already unmounted suspense boundary.`\n );\n }\n }\n const {\n vnode: vnode2,\n activeBranch,\n pendingBranch,\n pendingId,\n effects,\n parentComponent: parentComponent2,\n container: container2\n } = suspense;\n let delayEnter = false;\n if (suspense.isHydrating) {\n suspense.isHydrating = false;\n } else if (!resume) {\n delayEnter = activeBranch && pendingBranch.transition && pendingBranch.transition.mode === \"out-in\";\n if (delayEnter) {\n activeBranch.transition.afterLeave = () => {\n if (pendingId === suspense.pendingId) {\n move(\n pendingBranch,\n container2,\n anchor === initialAnchor ? next(activeBranch) : anchor,\n 0\n );\n queuePostFlushCb(effects);\n }\n };\n }\n if (activeBranch) {\n if (parentNode(activeBranch.el) !== suspense.hiddenContainer) {\n anchor = next(activeBranch);\n }\n unmount(activeBranch, parentComponent2, suspense, true);\n }\n if (!delayEnter) {\n move(pendingBranch, container2, anchor, 0);\n }\n }\n setActiveBranch(suspense, pendingBranch);\n suspense.pendingBranch = null;\n suspense.isInFallback = false;\n let parent = suspense.parent;\n let hasUnresolvedAncestor = false;\n while (parent) {\n if (parent.pendingBranch) {\n parent.effects.push(...effects);\n hasUnresolvedAncestor = true;\n break;\n }\n parent = parent.parent;\n }\n if (!hasUnresolvedAncestor && !delayEnter) {\n queuePostFlushCb(effects);\n }\n suspense.effects = [];\n if (isSuspensible) {\n if (parentSuspense && parentSuspense.pendingBranch && parentSuspenseId === parentSuspense.pendingId) {\n parentSuspense.deps--;\n if (parentSuspense.deps === 0 && !sync) {\n parentSuspense.resolve();\n }\n }\n }\n triggerEvent(vnode2, \"onResolve\");\n },\n fallback(fallbackVNode) {\n if (!suspense.pendingBranch) {\n return;\n }\n const { vnode: vnode2, activeBranch, parentComponent: parentComponent2, container: container2, namespace: namespace2 } = suspense;\n triggerEvent(vnode2, \"onFallback\");\n const anchor2 = next(activeBranch);\n const mountFallback = () => {\n if (!suspense.isInFallback) {\n return;\n }\n patch(\n null,\n fallbackVNode,\n container2,\n anchor2,\n parentComponent2,\n null,\n // fallback tree will not have suspense context\n namespace2,\n slotScopeIds,\n optimized\n );\n setActiveBranch(suspense, fallbackVNode);\n };\n const delayEnter = fallbackVNode.transition && fallbackVNode.transition.mode === \"out-in\";\n if (delayEnter) {\n activeBranch.transition.afterLeave = mountFallback;\n }\n suspense.isInFallback = true;\n unmount(\n activeBranch,\n parentComponent2,\n null,\n // no suspense so unmount hooks fire now\n true\n // shouldRemove\n );\n if (!delayEnter) {\n mountFallback();\n }\n },\n move(container2, anchor2, type) {\n suspense.activeBranch && move(suspense.activeBranch, container2, anchor2, type);\n suspense.container = container2;\n },\n next() {\n return suspense.activeBranch && next(suspense.activeBranch);\n },\n registerDep(instance, setupRenderEffect) {\n const isInPendingSuspense = !!suspense.pendingBranch;\n if (isInPendingSuspense) {\n suspense.deps++;\n }\n const hydratedEl = instance.vnode.el;\n instance.asyncDep.catch((err) => {\n handleError(err, instance, 0);\n }).then((asyncSetupResult) => {\n if (instance.isUnmounted || suspense.isUnmounted || suspense.pendingId !== instance.suspenseId) {\n return;\n }\n instance.asyncResolved = true;\n const { vnode: vnode2 } = instance;\n if (!!(process.env.NODE_ENV !== \"production\")) {\n pushWarningContext(vnode2);\n }\n handleSetupResult(instance, asyncSetupResult, false);\n if (hydratedEl) {\n vnode2.el = hydratedEl;\n }\n const placeholder = !hydratedEl && instance.subTree.el;\n setupRenderEffect(\n instance,\n vnode2,\n // component may have been moved before resolve.\n // if this is not a hydration, instance.subTree will be the comment\n // placeholder.\n parentNode(hydratedEl || instance.subTree.el),\n // anchor will not be used if this is hydration, so only need to\n // consider the comment placeholder case.\n hydratedEl ? null : next(instance.subTree),\n suspense,\n namespace,\n optimized\n );\n if (placeholder) {\n remove(placeholder);\n }\n updateHOCHostEl(instance, vnode2.el);\n if (!!(process.env.NODE_ENV !== \"production\")) {\n popWarningContext();\n }\n if (isInPendingSuspense && --suspense.deps === 0) {\n suspense.resolve();\n }\n });\n },\n unmount(parentSuspense2, doRemove) {\n suspense.isUnmounted = true;\n if (suspense.activeBranch) {\n unmount(\n suspense.activeBranch,\n parentComponent,\n parentSuspense2,\n doRemove\n );\n }\n if (suspense.pendingBranch) {\n unmount(\n suspense.pendingBranch,\n parentComponent,\n parentSuspense2,\n doRemove\n );\n }\n }\n };\n return suspense;\n}\nfunction hydrateSuspense(node, vnode, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, rendererInternals, hydrateNode) {\n const suspense = vnode.suspense = createSuspenseBoundary(\n vnode,\n parentSuspense,\n parentComponent,\n node.parentNode,\n // eslint-disable-next-line no-restricted-globals\n document.createElement(\"div\"),\n null,\n namespace,\n slotScopeIds,\n optimized,\n rendererInternals,\n true\n );\n const result = hydrateNode(\n node,\n suspense.pendingBranch = vnode.ssContent,\n parentComponent,\n suspense,\n slotScopeIds,\n optimized\n );\n if (suspense.deps === 0) {\n suspense.resolve(false, true);\n }\n return result;\n}\nfunction normalizeSuspenseChildren(vnode) {\n const { shapeFlag, children } = vnode;\n const isSlotChildren = shapeFlag & 32;\n vnode.ssContent = normalizeSuspenseSlot(\n isSlotChildren ? children.default : children\n );\n vnode.ssFallback = isSlotChildren ? normalizeSuspenseSlot(children.fallback) : createVNode(Comment);\n}\nfunction normalizeSuspenseSlot(s) {\n let block;\n if (isFunction(s)) {\n const trackBlock = isBlockTreeEnabled && s._c;\n if (trackBlock) {\n s._d = false;\n openBlock();\n }\n s = s();\n if (trackBlock) {\n s._d = true;\n block = currentBlock;\n closeBlock();\n }\n }\n if (isArray(s)) {\n const singleChild = filterSingleRoot(s);\n if (!!(process.env.NODE_ENV !== \"production\") && !singleChild && s.filter((child) => child !== NULL_DYNAMIC_COMPONENT).length > 0) {\n warn$1(` slots expect a single root node.`);\n }\n s = singleChild;\n }\n s = normalizeVNode(s);\n if (block && !s.dynamicChildren) {\n s.dynamicChildren = block.filter((c) => c !== s);\n }\n return s;\n}\nfunction queueEffectWithSuspense(fn, suspense) {\n if (suspense && suspense.pendingBranch) {\n if (isArray(fn)) {\n suspense.effects.push(...fn);\n } else {\n suspense.effects.push(fn);\n }\n } else {\n queuePostFlushCb(fn);\n }\n}\nfunction setActiveBranch(suspense, branch) {\n suspense.activeBranch = branch;\n const { vnode, parentComponent } = suspense;\n let el = branch.el;\n while (!el && branch.component) {\n branch = branch.component.subTree;\n el = branch.el;\n }\n vnode.el = el;\n if (parentComponent && parentComponent.subTree === vnode) {\n parentComponent.vnode.el = el;\n updateHOCHostEl(parentComponent, el);\n }\n}\nfunction isVNodeSuspensible(vnode) {\n var _a;\n return ((_a = vnode.props) == null ? void 0 : _a.suspensible) != null && vnode.props.suspensible !== false;\n}\n\nconst ssrContextKey = Symbol.for(\"v-scx\");\nconst useSSRContext = () => {\n {\n const ctx = inject(ssrContextKey);\n if (!ctx) {\n !!(process.env.NODE_ENV !== \"production\") && warn$1(\n `Server rendering context not provided. Make sure to only call useSSRContext() conditionally in the server build.`\n );\n }\n return ctx;\n }\n};\n\nfunction watchEffect(effect, options) {\n return doWatch(effect, null, options);\n}\nfunction watchPostEffect(effect, options) {\n return doWatch(\n effect,\n null,\n !!(process.env.NODE_ENV !== \"production\") ? extend({}, options, { flush: \"post\" }) : { flush: \"post\" }\n );\n}\nfunction watchSyncEffect(effect, options) {\n return doWatch(\n effect,\n null,\n !!(process.env.NODE_ENV !== \"production\") ? extend({}, options, { flush: \"sync\" }) : { flush: \"sync\" }\n );\n}\nconst INITIAL_WATCHER_VALUE = {};\nfunction watch(source, cb, options) {\n if (!!(process.env.NODE_ENV !== \"production\") && !isFunction(cb)) {\n warn$1(\n `\\`watch(fn, options?)\\` signature has been moved to a separate API. Use \\`watchEffect(fn, options?)\\` instead. \\`watch\\` now only supports \\`watch(source, cb, options?) signature.`\n );\n }\n return doWatch(source, cb, options);\n}\nfunction doWatch(source, cb, {\n immediate,\n deep,\n flush,\n once,\n onTrack,\n onTrigger\n} = EMPTY_OBJ) {\n if (cb && once) {\n const _cb = cb;\n cb = (...args) => {\n _cb(...args);\n unwatch();\n };\n }\n if (!!(process.env.NODE_ENV !== \"production\") && deep !== void 0 && typeof deep === \"number\") {\n warn$1(\n `watch() \"deep\" option with number value will be used as watch depth in future versions. Please use a boolean instead to avoid potential breakage.`\n );\n }\n if (!!(process.env.NODE_ENV !== \"production\") && !cb) {\n if (immediate !== void 0) {\n warn$1(\n `watch() \"immediate\" option is only respected when using the watch(source, callback, options?) signature.`\n );\n }\n if (deep !== void 0) {\n warn$1(\n `watch() \"deep\" option is only respected when using the watch(source, callback, options?) signature.`\n );\n }\n if (once !== void 0) {\n warn$1(\n `watch() \"once\" option is only respected when using the watch(source, callback, options?) signature.`\n );\n }\n }\n const warnInvalidSource = (s) => {\n warn$1(\n `Invalid watch source: `,\n s,\n `A watch source can only be a getter/effect function, a ref, a reactive object, or an array of these types.`\n );\n };\n const instance = currentInstance;\n const reactiveGetter = (source2) => deep === true ? source2 : (\n // for deep: false, only traverse root-level properties\n traverse(source2, deep === false ? 1 : void 0)\n );\n let getter;\n let forceTrigger = false;\n let isMultiSource = false;\n if (isRef(source)) {\n getter = () => source.value;\n forceTrigger = isShallow$1(source);\n } else if (isReactive(source)) {\n getter = () => reactiveGetter(source);\n forceTrigger = true;\n } else if (isArray(source)) {\n isMultiSource = true;\n forceTrigger = source.some((s) => isReactive(s) || isShallow$1(s));\n getter = () => source.map((s) => {\n if (isRef(s)) {\n return s.value;\n } else if (isReactive(s)) {\n return reactiveGetter(s);\n } else if (isFunction(s)) {\n return callWithErrorHandling(s, instance, 2);\n } else {\n !!(process.env.NODE_ENV !== \"production\") && warnInvalidSource(s);\n }\n });\n } else if (isFunction(source)) {\n if (cb) {\n getter = () => callWithErrorHandling(source, instance, 2);\n } else {\n getter = () => {\n if (cleanup) {\n cleanup();\n }\n return callWithAsyncErrorHandling(\n source,\n instance,\n 3,\n [onCleanup]\n );\n };\n }\n } else {\n getter = NOOP;\n !!(process.env.NODE_ENV !== \"production\") && warnInvalidSource(source);\n }\n if (cb && deep) {\n const baseGetter = getter;\n getter = () => traverse(baseGetter());\n }\n let cleanup;\n let onCleanup = (fn) => {\n cleanup = effect.onStop = () => {\n callWithErrorHandling(fn, instance, 4);\n cleanup = effect.onStop = void 0;\n };\n };\n let ssrCleanup;\n if (isInSSRComponentSetup) {\n onCleanup = NOOP;\n if (!cb) {\n getter();\n } else if (immediate) {\n callWithAsyncErrorHandling(cb, instance, 3, [\n getter(),\n isMultiSource ? [] : void 0,\n onCleanup\n ]);\n }\n if (flush === \"sync\") {\n const ctx = useSSRContext();\n ssrCleanup = ctx.__watcherHandles || (ctx.__watcherHandles = []);\n } else {\n return NOOP;\n }\n }\n let oldValue = isMultiSource ? new Array(source.length).fill(INITIAL_WATCHER_VALUE) : INITIAL_WATCHER_VALUE;\n const job = () => {\n if (!effect.active || !effect.dirty) {\n return;\n }\n if (cb) {\n const newValue = effect.run();\n if (deep || forceTrigger || (isMultiSource ? newValue.some((v, i) => hasChanged(v, oldValue[i])) : hasChanged(newValue, oldValue)) || false) {\n if (cleanup) {\n cleanup();\n }\n callWithAsyncErrorHandling(cb, instance, 3, [\n newValue,\n // pass undefined as the old value when it's changed for the first time\n oldValue === INITIAL_WATCHER_VALUE ? void 0 : isMultiSource && oldValue[0] === INITIAL_WATCHER_VALUE ? [] : oldValue,\n onCleanup\n ]);\n oldValue = newValue;\n }\n } else {\n effect.run();\n }\n };\n job.allowRecurse = !!cb;\n let scheduler;\n if (flush === \"sync\") {\n scheduler = job;\n } else if (flush === \"post\") {\n scheduler = () => queuePostRenderEffect(job, instance && instance.suspense);\n } else {\n job.pre = true;\n if (instance)\n job.id = instance.uid;\n scheduler = () => queueJob(job);\n }\n const effect = new ReactiveEffect(getter, NOOP, scheduler);\n const scope = getCurrentScope();\n const unwatch = () => {\n effect.stop();\n if (scope) {\n remove(scope.effects, effect);\n }\n };\n if (!!(process.env.NODE_ENV !== \"production\")) {\n effect.onTrack = onTrack;\n effect.onTrigger = onTrigger;\n }\n if (cb) {\n if (immediate) {\n job();\n } else {\n oldValue = effect.run();\n }\n } else if (flush === \"post\") {\n queuePostRenderEffect(\n effect.run.bind(effect),\n instance && instance.suspense\n );\n } else {\n effect.run();\n }\n if (ssrCleanup)\n ssrCleanup.push(unwatch);\n return unwatch;\n}\nfunction instanceWatch(source, value, options) {\n const publicThis = this.proxy;\n const getter = isString(source) ? source.includes(\".\") ? createPathGetter(publicThis, source) : () => publicThis[source] : source.bind(publicThis, publicThis);\n let cb;\n if (isFunction(value)) {\n cb = value;\n } else {\n cb = value.handler;\n options = value;\n }\n const reset = setCurrentInstance(this);\n const res = doWatch(getter, cb.bind(publicThis), options);\n reset();\n return res;\n}\nfunction createPathGetter(ctx, path) {\n const segments = path.split(\".\");\n return () => {\n let cur = ctx;\n for (let i = 0; i < segments.length && cur; i++) {\n cur = cur[segments[i]];\n }\n return cur;\n };\n}\nfunction traverse(value, depth, currentDepth = 0, seen) {\n if (!isObject(value) || value[\"__v_skip\"]) {\n return value;\n }\n if (depth && depth > 0) {\n if (currentDepth >= depth) {\n return value;\n }\n currentDepth++;\n }\n seen = seen || /* @__PURE__ */ new Set();\n if (seen.has(value)) {\n return value;\n }\n seen.add(value);\n if (isRef(value)) {\n traverse(value.value, depth, currentDepth, seen);\n } else if (isArray(value)) {\n for (let i = 0; i < value.length; i++) {\n traverse(value[i], depth, currentDepth, seen);\n }\n } else if (isSet(value) || isMap(value)) {\n value.forEach((v) => {\n traverse(v, depth, currentDepth, seen);\n });\n } else if (isPlainObject(value)) {\n for (const key in value) {\n traverse(value[key], depth, currentDepth, seen);\n }\n }\n return value;\n}\n\nfunction validateDirectiveName(name) {\n if (isBuiltInDirective(name)) {\n warn$1(\"Do not use built-in directive ids as custom directive id: \" + name);\n }\n}\nfunction withDirectives(vnode, directives) {\n if (currentRenderingInstance === null) {\n !!(process.env.NODE_ENV !== \"production\") && warn$1(`withDirectives can only be used inside render functions.`);\n return vnode;\n }\n const instance = getExposeProxy(currentRenderingInstance) || currentRenderingInstance.proxy;\n const bindings = vnode.dirs || (vnode.dirs = []);\n for (let i = 0; i < directives.length; i++) {\n let [dir, value, arg, modifiers = EMPTY_OBJ] = directives[i];\n if (dir) {\n if (isFunction(dir)) {\n dir = {\n mounted: dir,\n updated: dir\n };\n }\n if (dir.deep) {\n traverse(value);\n }\n bindings.push({\n dir,\n instance,\n value,\n oldValue: void 0,\n arg,\n modifiers\n });\n }\n }\n return vnode;\n}\nfunction invokeDirectiveHook(vnode, prevVNode, instance, name) {\n const bindings = vnode.dirs;\n const oldBindings = prevVNode && prevVNode.dirs;\n for (let i = 0; i < bindings.length; i++) {\n const binding = bindings[i];\n if (oldBindings) {\n binding.oldValue = oldBindings[i].value;\n }\n let hook = binding.dir[name];\n if (hook) {\n pauseTracking();\n callWithAsyncErrorHandling(hook, instance, 8, [\n vnode.el,\n binding,\n vnode,\n prevVNode\n ]);\n resetTracking();\n }\n }\n}\n\nconst leaveCbKey = Symbol(\"_leaveCb\");\nconst enterCbKey = Symbol(\"_enterCb\");\nfunction useTransitionState() {\n const state = {\n isMounted: false,\n isLeaving: false,\n isUnmounting: false,\n leavingVNodes: /* @__PURE__ */ new Map()\n };\n onMounted(() => {\n state.isMounted = true;\n });\n onBeforeUnmount(() => {\n state.isUnmounting = true;\n });\n return state;\n}\nconst TransitionHookValidator = [Function, Array];\nconst BaseTransitionPropsValidators = {\n mode: String,\n appear: Boolean,\n persisted: Boolean,\n // enter\n onBeforeEnter: TransitionHookValidator,\n onEnter: TransitionHookValidator,\n onAfterEnter: TransitionHookValidator,\n onEnterCancelled: TransitionHookValidator,\n // leave\n onBeforeLeave: TransitionHookValidator,\n onLeave: TransitionHookValidator,\n onAfterLeave: TransitionHookValidator,\n onLeaveCancelled: TransitionHookValidator,\n // appear\n onBeforeAppear: TransitionHookValidator,\n onAppear: TransitionHookValidator,\n onAfterAppear: TransitionHookValidator,\n onAppearCancelled: TransitionHookValidator\n};\nconst BaseTransitionImpl = {\n name: `BaseTransition`,\n props: BaseTransitionPropsValidators,\n setup(props, { slots }) {\n const instance = getCurrentInstance();\n const state = useTransitionState();\n let prevTransitionKey;\n return () => {\n const children = slots.default && getTransitionRawChildren(slots.default(), true);\n if (!children || !children.length) {\n return;\n }\n let child = children[0];\n if (children.length > 1) {\n let hasFound = false;\n for (const c of children) {\n if (c.type !== Comment) {\n if (!!(process.env.NODE_ENV !== \"production\") && hasFound) {\n warn$1(\n \" can only be used on a single element or component. Use for lists.\"\n );\n break;\n }\n child = c;\n hasFound = true;\n if (!!!(process.env.NODE_ENV !== \"production\"))\n break;\n }\n }\n }\n const rawProps = toRaw(props);\n const { mode } = rawProps;\n if (!!(process.env.NODE_ENV !== \"production\") && mode && mode !== \"in-out\" && mode !== \"out-in\" && mode !== \"default\") {\n warn$1(`invalid mode: ${mode}`);\n }\n if (state.isLeaving) {\n return emptyPlaceholder(child);\n }\n const innerChild = getKeepAliveChild(child);\n if (!innerChild) {\n return emptyPlaceholder(child);\n }\n const enterHooks = resolveTransitionHooks(\n innerChild,\n rawProps,\n state,\n instance\n );\n setTransitionHooks(innerChild, enterHooks);\n const oldChild = instance.subTree;\n const oldInnerChild = oldChild && getKeepAliveChild(oldChild);\n let transitionKeyChanged = false;\n const { getTransitionKey } = innerChild.type;\n if (getTransitionKey) {\n const key = getTransitionKey();\n if (prevTransitionKey === void 0) {\n prevTransitionKey = key;\n } else if (key !== prevTransitionKey) {\n prevTransitionKey = key;\n transitionKeyChanged = true;\n }\n }\n if (oldInnerChild && oldInnerChild.type !== Comment && (!isSameVNodeType(innerChild, oldInnerChild) || transitionKeyChanged)) {\n const leavingHooks = resolveTransitionHooks(\n oldInnerChild,\n rawProps,\n state,\n instance\n );\n setTransitionHooks(oldInnerChild, leavingHooks);\n if (mode === \"out-in\") {\n state.isLeaving = true;\n leavingHooks.afterLeave = () => {\n state.isLeaving = false;\n if (instance.update.active !== false) {\n instance.effect.dirty = true;\n instance.update();\n }\n };\n return emptyPlaceholder(child);\n } else if (mode === \"in-out\" && innerChild.type !== Comment) {\n leavingHooks.delayLeave = (el, earlyRemove, delayedLeave) => {\n const leavingVNodesCache = getLeavingNodesForType(\n state,\n oldInnerChild\n );\n leavingVNodesCache[String(oldInnerChild.key)] = oldInnerChild;\n el[leaveCbKey] = () => {\n earlyRemove();\n el[leaveCbKey] = void 0;\n delete enterHooks.delayedLeave;\n };\n enterHooks.delayedLeave = delayedLeave;\n };\n }\n }\n return child;\n };\n }\n};\nconst BaseTransition = BaseTransitionImpl;\nfunction getLeavingNodesForType(state, vnode) {\n const { leavingVNodes } = state;\n let leavingVNodesCache = leavingVNodes.get(vnode.type);\n if (!leavingVNodesCache) {\n leavingVNodesCache = /* @__PURE__ */ Object.create(null);\n leavingVNodes.set(vnode.type, leavingVNodesCache);\n }\n return leavingVNodesCache;\n}\nfunction resolveTransitionHooks(vnode, props, state, instance) {\n const {\n appear,\n mode,\n persisted = false,\n onBeforeEnter,\n onEnter,\n onAfterEnter,\n onEnterCancelled,\n onBeforeLeave,\n onLeave,\n onAfterLeave,\n onLeaveCancelled,\n onBeforeAppear,\n onAppear,\n onAfterAppear,\n onAppearCancelled\n } = props;\n const key = String(vnode.key);\n const leavingVNodesCache = getLeavingNodesForType(state, vnode);\n const callHook = (hook, args) => {\n hook && callWithAsyncErrorHandling(\n hook,\n instance,\n 9,\n args\n );\n };\n const callAsyncHook = (hook, args) => {\n const done = args[1];\n callHook(hook, args);\n if (isArray(hook)) {\n if (hook.every((hook2) => hook2.length <= 1))\n done();\n } else if (hook.length <= 1) {\n done();\n }\n };\n const hooks = {\n mode,\n persisted,\n beforeEnter(el) {\n let hook = onBeforeEnter;\n if (!state.isMounted) {\n if (appear) {\n hook = onBeforeAppear || onBeforeEnter;\n } else {\n return;\n }\n }\n if (el[leaveCbKey]) {\n el[leaveCbKey](\n true\n /* cancelled */\n );\n }\n const leavingVNode = leavingVNodesCache[key];\n if (leavingVNode && isSameVNodeType(vnode, leavingVNode) && leavingVNode.el[leaveCbKey]) {\n leavingVNode.el[leaveCbKey]();\n }\n callHook(hook, [el]);\n },\n enter(el) {\n let hook = onEnter;\n let afterHook = onAfterEnter;\n let cancelHook = onEnterCancelled;\n if (!state.isMounted) {\n if (appear) {\n hook = onAppear || onEnter;\n afterHook = onAfterAppear || onAfterEnter;\n cancelHook = onAppearCancelled || onEnterCancelled;\n } else {\n return;\n }\n }\n let called = false;\n const done = el[enterCbKey] = (cancelled) => {\n if (called)\n return;\n called = true;\n if (cancelled) {\n callHook(cancelHook, [el]);\n } else {\n callHook(afterHook, [el]);\n }\n if (hooks.delayedLeave) {\n hooks.delayedLeave();\n }\n el[enterCbKey] = void 0;\n };\n if (hook) {\n callAsyncHook(hook, [el, done]);\n } else {\n done();\n }\n },\n leave(el, remove) {\n const key2 = String(vnode.key);\n if (el[enterCbKey]) {\n el[enterCbKey](\n true\n /* cancelled */\n );\n }\n if (state.isUnmounting) {\n return remove();\n }\n callHook(onBeforeLeave, [el]);\n let called = false;\n const done = el[leaveCbKey] = (cancelled) => {\n if (called)\n return;\n called = true;\n remove();\n if (cancelled) {\n callHook(onLeaveCancelled, [el]);\n } else {\n callHook(onAfterLeave, [el]);\n }\n el[leaveCbKey] = void 0;\n if (leavingVNodesCache[key2] === vnode) {\n delete leavingVNodesCache[key2];\n }\n };\n leavingVNodesCache[key2] = vnode;\n if (onLeave) {\n callAsyncHook(onLeave, [el, done]);\n } else {\n done();\n }\n },\n clone(vnode2) {\n return resolveTransitionHooks(vnode2, props, state, instance);\n }\n };\n return hooks;\n}\nfunction emptyPlaceholder(vnode) {\n if (isKeepAlive(vnode)) {\n vnode = cloneVNode(vnode);\n vnode.children = null;\n return vnode;\n }\n}\nfunction getKeepAliveChild(vnode) {\n return isKeepAlive(vnode) ? (\n // #7121 ensure get the child component subtree in case\n // it's been replaced during HMR\n !!(process.env.NODE_ENV !== \"production\") && vnode.component ? vnode.component.subTree : vnode.children ? vnode.children[0] : void 0\n ) : vnode;\n}\nfunction setTransitionHooks(vnode, hooks) {\n if (vnode.shapeFlag & 6 && vnode.component) {\n setTransitionHooks(vnode.component.subTree, hooks);\n } else if (vnode.shapeFlag & 128) {\n vnode.ssContent.transition = hooks.clone(vnode.ssContent);\n vnode.ssFallback.transition = hooks.clone(vnode.ssFallback);\n } else {\n vnode.transition = hooks;\n }\n}\nfunction getTransitionRawChildren(children, keepComment = false, parentKey) {\n let ret = [];\n let keyedFragmentCount = 0;\n for (let i = 0; i < children.length; i++) {\n let child = children[i];\n const key = parentKey == null ? child.key : String(parentKey) + String(child.key != null ? child.key : i);\n if (child.type === Fragment) {\n if (child.patchFlag & 128)\n keyedFragmentCount++;\n ret = ret.concat(\n getTransitionRawChildren(child.children, keepComment, key)\n );\n } else if (keepComment || child.type !== Comment) {\n ret.push(key != null ? cloneVNode(child, { key }) : child);\n }\n }\n if (keyedFragmentCount > 1) {\n for (let i = 0; i < ret.length; i++) {\n ret[i].patchFlag = -2;\n }\n }\n return ret;\n}\n\n/*! #__NO_SIDE_EFFECTS__ */\n// @__NO_SIDE_EFFECTS__\nfunction defineComponent(options, extraOptions) {\n return isFunction(options) ? (\n // #8326: extend call and options.name access are considered side-effects\n // by Rollup, so we have to wrap it in a pure-annotated IIFE.\n /* @__PURE__ */ (() => extend({ name: options.name }, extraOptions, { setup: options }))()\n ) : options;\n}\n\nconst isAsyncWrapper = (i) => !!i.type.__asyncLoader;\n/*! #__NO_SIDE_EFFECTS__ */\n// @__NO_SIDE_EFFECTS__\nfunction defineAsyncComponent(source) {\n if (isFunction(source)) {\n source = { loader: source };\n }\n const {\n loader,\n loadingComponent,\n errorComponent,\n delay = 200,\n timeout,\n // undefined = never times out\n suspensible = true,\n onError: userOnError\n } = source;\n let pendingRequest = null;\n let resolvedComp;\n let retries = 0;\n const retry = () => {\n retries++;\n pendingRequest = null;\n return load();\n };\n const load = () => {\n let thisRequest;\n return pendingRequest || (thisRequest = pendingRequest = loader().catch((err) => {\n err = err instanceof Error ? err : new Error(String(err));\n if (userOnError) {\n return new Promise((resolve, reject) => {\n const userRetry = () => resolve(retry());\n const userFail = () => reject(err);\n userOnError(err, userRetry, userFail, retries + 1);\n });\n } else {\n throw err;\n }\n }).then((comp) => {\n if (thisRequest !== pendingRequest && pendingRequest) {\n return pendingRequest;\n }\n if (!!(process.env.NODE_ENV !== \"production\") && !comp) {\n warn$1(\n `Async component loader resolved to undefined. If you are using retry(), make sure to return its return value.`\n );\n }\n if (comp && (comp.__esModule || comp[Symbol.toStringTag] === \"Module\")) {\n comp = comp.default;\n }\n if (!!(process.env.NODE_ENV !== \"production\") && comp && !isObject(comp) && !isFunction(comp)) {\n throw new Error(`Invalid async component load result: ${comp}`);\n }\n resolvedComp = comp;\n return comp;\n }));\n };\n return defineComponent({\n name: \"AsyncComponentWrapper\",\n __asyncLoader: load,\n get __asyncResolved() {\n return resolvedComp;\n },\n setup() {\n const instance = currentInstance;\n if (resolvedComp) {\n return () => createInnerComp(resolvedComp, instance);\n }\n const onError = (err) => {\n pendingRequest = null;\n handleError(\n err,\n instance,\n 13,\n !errorComponent\n );\n };\n if (suspensible && instance.suspense || isInSSRComponentSetup) {\n return load().then((comp) => {\n return () => createInnerComp(comp, instance);\n }).catch((err) => {\n onError(err);\n return () => errorComponent ? createVNode(errorComponent, {\n error: err\n }) : null;\n });\n }\n const loaded = ref(false);\n const error = ref();\n const delayed = ref(!!delay);\n if (delay) {\n setTimeout(() => {\n delayed.value = false;\n }, delay);\n }\n if (timeout != null) {\n setTimeout(() => {\n if (!loaded.value && !error.value) {\n const err = new Error(\n `Async component timed out after ${timeout}ms.`\n );\n onError(err);\n error.value = err;\n }\n }, timeout);\n }\n load().then(() => {\n loaded.value = true;\n if (instance.parent && isKeepAlive(instance.parent.vnode)) {\n instance.parent.effect.dirty = true;\n queueJob(instance.parent.update);\n }\n }).catch((err) => {\n onError(err);\n error.value = err;\n });\n return () => {\n if (loaded.value && resolvedComp) {\n return createInnerComp(resolvedComp, instance);\n } else if (error.value && errorComponent) {\n return createVNode(errorComponent, {\n error: error.value\n });\n } else if (loadingComponent && !delayed.value) {\n return createVNode(loadingComponent);\n }\n };\n }\n });\n}\nfunction createInnerComp(comp, parent) {\n const { ref: ref2, props, children, ce } = parent.vnode;\n const vnode = createVNode(comp, props, children);\n vnode.ref = ref2;\n vnode.ce = ce;\n delete parent.vnode.ce;\n return vnode;\n}\n\nconst isKeepAlive = (vnode) => vnode.type.__isKeepAlive;\nconst KeepAliveImpl = {\n name: `KeepAlive`,\n // Marker for special handling inside the renderer. We are not using a ===\n // check directly on KeepAlive in the renderer, because importing it directly\n // would prevent it from being tree-shaken.\n __isKeepAlive: true,\n props: {\n include: [String, RegExp, Array],\n exclude: [String, RegExp, Array],\n max: [String, Number]\n },\n setup(props, { slots }) {\n const instance = getCurrentInstance();\n const sharedContext = instance.ctx;\n if (!sharedContext.renderer) {\n return () => {\n const children = slots.default && slots.default();\n return children && children.length === 1 ? children[0] : children;\n };\n }\n const cache = /* @__PURE__ */ new Map();\n const keys = /* @__PURE__ */ new Set();\n let current = null;\n if (!!(process.env.NODE_ENV !== \"production\") || __VUE_PROD_DEVTOOLS__) {\n instance.__v_cache = cache;\n }\n const parentSuspense = instance.suspense;\n const {\n renderer: {\n p: patch,\n m: move,\n um: _unmount,\n o: { createElement }\n }\n } = sharedContext;\n const storageContainer = createElement(\"div\");\n sharedContext.activate = (vnode, container, anchor, namespace, optimized) => {\n const instance2 = vnode.component;\n move(vnode, container, anchor, 0, parentSuspense);\n patch(\n instance2.vnode,\n vnode,\n container,\n anchor,\n instance2,\n parentSuspense,\n namespace,\n vnode.slotScopeIds,\n optimized\n );\n queuePostRenderEffect(() => {\n instance2.isDeactivated = false;\n if (instance2.a) {\n invokeArrayFns(instance2.a);\n }\n const vnodeHook = vnode.props && vnode.props.onVnodeMounted;\n if (vnodeHook) {\n invokeVNodeHook(vnodeHook, instance2.parent, vnode);\n }\n }, parentSuspense);\n if (!!(process.env.NODE_ENV !== \"production\") || __VUE_PROD_DEVTOOLS__) {\n devtoolsComponentAdded(instance2);\n }\n };\n sharedContext.deactivate = (vnode) => {\n const instance2 = vnode.component;\n move(vnode, storageContainer, null, 1, parentSuspense);\n queuePostRenderEffect(() => {\n if (instance2.da) {\n invokeArrayFns(instance2.da);\n }\n const vnodeHook = vnode.props && vnode.props.onVnodeUnmounted;\n if (vnodeHook) {\n invokeVNodeHook(vnodeHook, instance2.parent, vnode);\n }\n instance2.isDeactivated = true;\n }, parentSuspense);\n if (!!(process.env.NODE_ENV !== \"production\") || __VUE_PROD_DEVTOOLS__) {\n devtoolsComponentAdded(instance2);\n }\n };\n function unmount(vnode) {\n resetShapeFlag(vnode);\n _unmount(vnode, instance, parentSuspense, true);\n }\n function pruneCache(filter) {\n cache.forEach((vnode, key) => {\n const name = getComponentName(vnode.type);\n if (name && (!filter || !filter(name))) {\n pruneCacheEntry(key);\n }\n });\n }\n function pruneCacheEntry(key) {\n const cached = cache.get(key);\n if (!current || !isSameVNodeType(cached, current)) {\n unmount(cached);\n } else if (current) {\n resetShapeFlag(current);\n }\n cache.delete(key);\n keys.delete(key);\n }\n watch(\n () => [props.include, props.exclude],\n ([include, exclude]) => {\n include && pruneCache((name) => matches(include, name));\n exclude && pruneCache((name) => !matches(exclude, name));\n },\n // prune post-render after `current` has been updated\n { flush: \"post\", deep: true }\n );\n let pendingCacheKey = null;\n const cacheSubtree = () => {\n if (pendingCacheKey != null) {\n cache.set(pendingCacheKey, getInnerChild(instance.subTree));\n }\n };\n onMounted(cacheSubtree);\n onUpdated(cacheSubtree);\n onBeforeUnmount(() => {\n cache.forEach((cached) => {\n const { subTree, suspense } = instance;\n const vnode = getInnerChild(subTree);\n if (cached.type === vnode.type && cached.key === vnode.key) {\n resetShapeFlag(vnode);\n const da = vnode.component.da;\n da && queuePostRenderEffect(da, suspense);\n return;\n }\n unmount(cached);\n });\n });\n return () => {\n pendingCacheKey = null;\n if (!slots.default) {\n return null;\n }\n const children = slots.default();\n const rawVNode = children[0];\n if (children.length > 1) {\n if (!!(process.env.NODE_ENV !== \"production\")) {\n warn$1(`KeepAlive should contain exactly one component child.`);\n }\n current = null;\n return children;\n } else if (!isVNode(rawVNode) || !(rawVNode.shapeFlag & 4) && !(rawVNode.shapeFlag & 128)) {\n current = null;\n return rawVNode;\n }\n let vnode = getInnerChild(rawVNode);\n const comp = vnode.type;\n const name = getComponentName(\n isAsyncWrapper(vnode) ? vnode.type.__asyncResolved || {} : comp\n );\n const { include, exclude, max } = props;\n if (include && (!name || !matches(include, name)) || exclude && name && matches(exclude, name)) {\n current = vnode;\n return rawVNode;\n }\n const key = vnode.key == null ? comp : vnode.key;\n const cachedVNode = cache.get(key);\n if (vnode.el) {\n vnode = cloneVNode(vnode);\n if (rawVNode.shapeFlag & 128) {\n rawVNode.ssContent = vnode;\n }\n }\n pendingCacheKey = key;\n if (cachedVNode) {\n vnode.el = cachedVNode.el;\n vnode.component = cachedVNode.component;\n if (vnode.transition) {\n setTransitionHooks(vnode, vnode.transition);\n }\n vnode.shapeFlag |= 512;\n keys.delete(key);\n keys.add(key);\n } else {\n keys.add(key);\n if (max && keys.size > parseInt(max, 10)) {\n pruneCacheEntry(keys.values().next().value);\n }\n }\n vnode.shapeFlag |= 256;\n current = vnode;\n return isSuspense(rawVNode.type) ? rawVNode : vnode;\n };\n }\n};\nconst KeepAlive = KeepAliveImpl;\nfunction matches(pattern, name) {\n if (isArray(pattern)) {\n return pattern.some((p) => matches(p, name));\n } else if (isString(pattern)) {\n return pattern.split(\",\").includes(name);\n } else if (isRegExp(pattern)) {\n return pattern.test(name);\n }\n return false;\n}\nfunction onActivated(hook, target) {\n registerKeepAliveHook(hook, \"a\", target);\n}\nfunction onDeactivated(hook, target) {\n registerKeepAliveHook(hook, \"da\", target);\n}\nfunction registerKeepAliveHook(hook, type, target = currentInstance) {\n const wrappedHook = hook.__wdc || (hook.__wdc = () => {\n let current = target;\n while (current) {\n if (current.isDeactivated) {\n return;\n }\n current = current.parent;\n }\n return hook();\n });\n injectHook(type, wrappedHook, target);\n if (target) {\n let current = target.parent;\n while (current && current.parent) {\n if (isKeepAlive(current.parent.vnode)) {\n injectToKeepAliveRoot(wrappedHook, type, target, current);\n }\n current = current.parent;\n }\n }\n}\nfunction injectToKeepAliveRoot(hook, type, target, keepAliveRoot) {\n const injected = injectHook(\n type,\n hook,\n keepAliveRoot,\n true\n /* prepend */\n );\n onUnmounted(() => {\n remove(keepAliveRoot[type], injected);\n }, target);\n}\nfunction resetShapeFlag(vnode) {\n vnode.shapeFlag &= ~256;\n vnode.shapeFlag &= ~512;\n}\nfunction getInnerChild(vnode) {\n return vnode.shapeFlag & 128 ? vnode.ssContent : vnode;\n}\n\nfunction injectHook(type, hook, target = currentInstance, prepend = false) {\n if (target) {\n const hooks = target[type] || (target[type] = []);\n const wrappedHook = hook.__weh || (hook.__weh = (...args) => {\n if (target.isUnmounted) {\n return;\n }\n pauseTracking();\n const reset = setCurrentInstance(target);\n const res = callWithAsyncErrorHandling(hook, target, type, args);\n reset();\n resetTracking();\n return res;\n });\n if (prepend) {\n hooks.unshift(wrappedHook);\n } else {\n hooks.push(wrappedHook);\n }\n return wrappedHook;\n } else if (!!(process.env.NODE_ENV !== \"production\")) {\n const apiName = toHandlerKey(ErrorTypeStrings$1[type].replace(/ hook$/, \"\"));\n warn$1(\n `${apiName} is called when there is no active component instance to be associated with. Lifecycle injection APIs can only be used during execution of setup().` + (` If you are using async setup(), make sure to register lifecycle hooks before the first await statement.` )\n );\n }\n}\nconst createHook = (lifecycle) => (hook, target = currentInstance) => (\n // post-create lifecycle registrations are noops during SSR (except for serverPrefetch)\n (!isInSSRComponentSetup || lifecycle === \"sp\") && injectHook(lifecycle, (...args) => hook(...args), target)\n);\nconst onBeforeMount = createHook(\"bm\");\nconst onMounted = createHook(\"m\");\nconst onBeforeUpdate = createHook(\"bu\");\nconst onUpdated = createHook(\"u\");\nconst onBeforeUnmount = createHook(\"bum\");\nconst onUnmounted = createHook(\"um\");\nconst onServerPrefetch = createHook(\"sp\");\nconst onRenderTriggered = createHook(\n \"rtg\"\n);\nconst onRenderTracked = createHook(\n \"rtc\"\n);\nfunction onErrorCaptured(hook, target = currentInstance) {\n injectHook(\"ec\", hook, target);\n}\n\nfunction renderList(source, renderItem, cache, index) {\n let ret;\n const cached = cache && cache[index];\n if (isArray(source) || isString(source)) {\n ret = new Array(source.length);\n for (let i = 0, l = source.length; i < l; i++) {\n ret[i] = renderItem(source[i], i, void 0, cached && cached[i]);\n }\n } else if (typeof source === \"number\") {\n if (!!(process.env.NODE_ENV !== \"production\") && !Number.isInteger(source)) {\n warn$1(`The v-for range expect an integer value but got ${source}.`);\n }\n ret = new Array(source);\n for (let i = 0; i < source; i++) {\n ret[i] = renderItem(i + 1, i, void 0, cached && cached[i]);\n }\n } else if (isObject(source)) {\n if (source[Symbol.iterator]) {\n ret = Array.from(\n source,\n (item, i) => renderItem(item, i, void 0, cached && cached[i])\n );\n } else {\n const keys = Object.keys(source);\n ret = new Array(keys.length);\n for (let i = 0, l = keys.length; i < l; i++) {\n const key = keys[i];\n ret[i] = renderItem(source[key], key, i, cached && cached[i]);\n }\n }\n } else {\n ret = [];\n }\n if (cache) {\n cache[index] = ret;\n }\n return ret;\n}\n\nfunction createSlots(slots, dynamicSlots) {\n for (let i = 0; i < dynamicSlots.length; i++) {\n const slot = dynamicSlots[i];\n if (isArray(slot)) {\n for (let j = 0; j < slot.length; j++) {\n slots[slot[j].name] = slot[j].fn;\n }\n } else if (slot) {\n slots[slot.name] = slot.key ? (...args) => {\n const res = slot.fn(...args);\n if (res)\n res.key = slot.key;\n return res;\n } : slot.fn;\n }\n }\n return slots;\n}\n\nfunction renderSlot(slots, name, props = {}, fallback, noSlotted) {\n if (currentRenderingInstance.isCE || currentRenderingInstance.parent && isAsyncWrapper(currentRenderingInstance.parent) && currentRenderingInstance.parent.isCE) {\n if (name !== \"default\")\n props.name = name;\n return createVNode(\"slot\", props, fallback && fallback());\n }\n let slot = slots[name];\n if (!!(process.env.NODE_ENV !== \"production\") && slot && slot.length > 1) {\n warn$1(\n `SSR-optimized slot function detected in a non-SSR-optimized render function. You need to mark this component with $dynamic-slots in the parent template.`\n );\n slot = () => [];\n }\n if (slot && slot._c) {\n slot._d = false;\n }\n openBlock();\n const validSlotContent = slot && ensureValidVNode(slot(props));\n const rendered = createBlock(\n Fragment,\n {\n key: props.key || // slot content array of a dynamic conditional slot may have a branch\n // key attached in the `createSlots` helper, respect that\n validSlotContent && validSlotContent.key || `_${name}`\n },\n validSlotContent || (fallback ? fallback() : []),\n validSlotContent && slots._ === 1 ? 64 : -2\n );\n if (!noSlotted && rendered.scopeId) {\n rendered.slotScopeIds = [rendered.scopeId + \"-s\"];\n }\n if (slot && slot._c) {\n slot._d = true;\n }\n return rendered;\n}\nfunction ensureValidVNode(vnodes) {\n return vnodes.some((child) => {\n if (!isVNode(child))\n return true;\n if (child.type === Comment)\n return false;\n if (child.type === Fragment && !ensureValidVNode(child.children))\n return false;\n return true;\n }) ? vnodes : null;\n}\n\nfunction toHandlers(obj, preserveCaseIfNecessary) {\n const ret = {};\n if (!!(process.env.NODE_ENV !== \"production\") && !isObject(obj)) {\n warn$1(`v-on with no argument expects an object value.`);\n return ret;\n }\n for (const key in obj) {\n ret[preserveCaseIfNecessary && /[A-Z]/.test(key) ? `on:${key}` : toHandlerKey(key)] = obj[key];\n }\n return ret;\n}\n\nconst getPublicInstance = (i) => {\n if (!i)\n return null;\n if (isStatefulComponent(i))\n return getExposeProxy(i) || i.proxy;\n return getPublicInstance(i.parent);\n};\nconst publicPropertiesMap = (\n // Move PURE marker to new line to workaround compiler discarding it\n // due to type annotation\n /* @__PURE__ */ extend(/* @__PURE__ */ Object.create(null), {\n $: (i) => i,\n $el: (i) => i.vnode.el,\n $data: (i) => i.data,\n $props: (i) => !!(process.env.NODE_ENV !== \"production\") ? shallowReadonly(i.props) : i.props,\n $attrs: (i) => !!(process.env.NODE_ENV !== \"production\") ? shallowReadonly(i.attrs) : i.attrs,\n $slots: (i) => !!(process.env.NODE_ENV !== \"production\") ? shallowReadonly(i.slots) : i.slots,\n $refs: (i) => !!(process.env.NODE_ENV !== \"production\") ? shallowReadonly(i.refs) : i.refs,\n $parent: (i) => getPublicInstance(i.parent),\n $root: (i) => getPublicInstance(i.root),\n $emit: (i) => i.emit,\n $options: (i) => __VUE_OPTIONS_API__ ? resolveMergedOptions(i) : i.type,\n $forceUpdate: (i) => i.f || (i.f = () => {\n i.effect.dirty = true;\n queueJob(i.update);\n }),\n $nextTick: (i) => i.n || (i.n = nextTick.bind(i.proxy)),\n $watch: (i) => __VUE_OPTIONS_API__ ? instanceWatch.bind(i) : NOOP\n })\n);\nconst isReservedPrefix = (key) => key === \"_\" || key === \"$\";\nconst hasSetupBinding = (state, key) => state !== EMPTY_OBJ && !state.__isScriptSetup && hasOwn(state, key);\nconst PublicInstanceProxyHandlers = {\n get({ _: instance }, key) {\n const { ctx, setupState, data, props, accessCache, type, appContext } = instance;\n if (!!(process.env.NODE_ENV !== \"production\") && key === \"__isVue\") {\n return true;\n }\n let normalizedProps;\n if (key[0] !== \"$\") {\n const n = accessCache[key];\n if (n !== void 0) {\n switch (n) {\n case 1 /* SETUP */:\n return setupState[key];\n case 2 /* DATA */:\n return data[key];\n case 4 /* CONTEXT */:\n return ctx[key];\n case 3 /* PROPS */:\n return props[key];\n }\n } else if (hasSetupBinding(setupState, key)) {\n accessCache[key] = 1 /* SETUP */;\n return setupState[key];\n } else if (data !== EMPTY_OBJ && hasOwn(data, key)) {\n accessCache[key] = 2 /* DATA */;\n return data[key];\n } else if (\n // only cache other properties when instance has declared (thus stable)\n // props\n (normalizedProps = instance.propsOptions[0]) && hasOwn(normalizedProps, key)\n ) {\n accessCache[key] = 3 /* PROPS */;\n return props[key];\n } else if (ctx !== EMPTY_OBJ && hasOwn(ctx, key)) {\n accessCache[key] = 4 /* CONTEXT */;\n return ctx[key];\n } else if (!__VUE_OPTIONS_API__ || shouldCacheAccess) {\n accessCache[key] = 0 /* OTHER */;\n }\n }\n const publicGetter = publicPropertiesMap[key];\n let cssModule, globalProperties;\n if (publicGetter) {\n if (key === \"$attrs\") {\n track(instance, \"get\", key);\n !!(process.env.NODE_ENV !== \"production\") && markAttrsAccessed();\n } else if (!!(process.env.NODE_ENV !== \"production\") && key === \"$slots\") {\n track(instance, \"get\", key);\n }\n return publicGetter(instance);\n } else if (\n // css module (injected by vue-loader)\n (cssModule = type.__cssModules) && (cssModule = cssModule[key])\n ) {\n return cssModule;\n } else if (ctx !== EMPTY_OBJ && hasOwn(ctx, key)) {\n accessCache[key] = 4 /* CONTEXT */;\n return ctx[key];\n } else if (\n // global properties\n globalProperties = appContext.config.globalProperties, hasOwn(globalProperties, key)\n ) {\n {\n return globalProperties[key];\n }\n } else if (!!(process.env.NODE_ENV !== \"production\") && currentRenderingInstance && (!isString(key) || // #1091 avoid internal isRef/isVNode checks on component instance leading\n // to infinite warning loop\n key.indexOf(\"__v\") !== 0)) {\n if (data !== EMPTY_OBJ && isReservedPrefix(key[0]) && hasOwn(data, key)) {\n warn$1(\n `Property ${JSON.stringify(\n key\n )} must be accessed via $data because it starts with a reserved character (\"$\" or \"_\") and is not proxied on the render context.`\n );\n } else if (instance === currentRenderingInstance) {\n warn$1(\n `Property ${JSON.stringify(key)} was accessed during render but is not defined on instance.`\n );\n }\n }\n },\n set({ _: instance }, key, value) {\n const { data, setupState, ctx } = instance;\n if (hasSetupBinding(setupState, key)) {\n setupState[key] = value;\n return true;\n } else if (!!(process.env.NODE_ENV !== \"production\") && setupState.__isScriptSetup && hasOwn(setupState, key)) {\n warn$1(`Cannot mutate \n","\n\n\n\n\n","\n\n\n","\n\n\n\n\n","export const flatten = (node, descend = true) => {\n if (!node) {\n throw new Error('Invalid \"node\" parameter');\n }\n\n const result = [];\n\n node.descendants((child, pos) => {\n result.push({ node: child, pos });\n if (!descend) {\n return false;\n }\n });\n\n return result;\n};\n\nexport const findChildren = (node, predicate, descend) => {\n if (!node) {\n throw new Error('Invalid \"node\" parameter');\n } else if (!predicate) {\n throw new Error('Invalid \"predicate\" parameter');\n }\n\n return flatten(node, descend).filter((child) => { return predicate(child.node); });\n};\n\nexport const findTextNodes = (node, descend) => {\n return findChildren(node, (child) => { return child.isText; }, descend);\n};\n\nexport const findInlineNodes = (node, descend) => {\n return findChildren(node, (child) => { return child.isInline; }, descend);\n};\n\nexport const findBlockNodes = (node, descend) => {\n return findChildren(node, (child) => { return child.isBlock; }, descend);\n};\n\nexport const findChildrenByAttr = (node, predicate, descend) => {\n return findChildren(node, (child) => { return !!predicate(child.attrs); }, descend);\n};\n\nexport const findChildrenByType = (node, nodeType, descend) => {\n return findChildren(node, (child) => { return child.type === nodeType; }, descend);\n};\n\nexport const findChildrenByMark = (node, markType, descend) => {\n return findChildren(node, (child) => { return markType.isInSet(child.marks); }, descend);\n};\n\nexport const contains = (node, nodeType) => {\n return !!findChildrenByType(node, nodeType).length;\n};\n","export default {\n name: 'followCursor',\n defaultValue: false,\n fn(instance) {\n const { reference } = instance;\n\n return {\n onMount() {\n const event = instance.props.mouseEvent;\n const isCursorOverReference = event.target ? reference.contains(event.target) : true;\n const { clientX, clientY } = event;\n\n const rect = reference.getBoundingClientRect();\n const relativeX = clientX - rect.left;\n const relativeY = clientY - rect.top;\n\n if (isCursorOverReference || !instance.props.interactive) {\n instance.setProps({\n getReferenceClientRect() {\n const rect = reference.getBoundingClientRect();\n\n const x = rect.left + relativeX;\n const y = rect.top + relativeY;\n\n return {\n width: 0,\n height: 0,\n top: y,\n right: x,\n bottom: y,\n left: x,\n };\n },\n });\n }\n },\n };\n },\n};\n","\n\n\n\n\n","\n\n\n","\n\n\n\n\n","\n\n\n\n\n","\n\n\n","\n\n\n\n\n","\n\n\n\n\n","\n\n\n","\n\n\n\n\n","import { isNodeEmpty } from '@tiptap/core';\nimport { Plugin, PluginKey } from 'prosemirror-state';\n\nclass Menu {\n constructor({ options, editorView }) {\n this.options = {\n ...{\n element: null,\n onUpdate: () => { return false; },\n },\n ...options,\n };\n\n this.preventHide = false;\n this.editorView = editorView;\n this.isActive = false;\n this.top = 0;\n this.behaviour = this.options.editor.vizyField.settings.blockTypeBehaviour;\n\n if (this.behaviour === 'click') {\n this.options.element.addEventListener('mousedown', this.mousedownHandler.bind(this), { capture: true });\n this.options.editor.on('focus', this.focusHandler.bind(this));\n this.options.editor.on('blur', this.blurHandler.bind(this));\n this.options.editor.on('resize', this.resizeHandler.bind(this));\n }\n\n if (this.behaviour === 'hover') {\n this.options.editor.view.dom.addEventListener('mousemove', this.mouseenterHandler.bind(this));\n this.options.editor.view.dom.addEventListener('mouseleave', this.mouseleaveHandler.bind(this));\n }\n }\n\n mouseenterHandler(e) {\n const { view } = this.options.editor;\n const pos = view.posAtCoords({ left: e.clientX, top: e.clientY });\n\n if (pos.pos && pos.inside > -1) {\n const position = pos.pos;\n const node = view.state.doc.resolve(position).parent;\n\n if (isNodeEmpty(node)) {\n setTimeout(() => {\n const parent = this.options.element.offsetParent;\n\n if (parent) {\n const parentBox = parent.getBoundingClientRect();\n const cursorCoords = view.coordsAtPos(position);\n const top = cursorCoords.top - parentBox.top;\n\n this.isActive = true;\n this.top = top;\n\n // Record the position against the field, so we can use it to set the cursor\n this.options.editor.vizyField.currentNodeHoverPosition = position;\n\n this.sendUpdate();\n }\n }, 10);\n } else {\n this.hide();\n }\n }\n }\n\n mouseleaveHandler(event) {\n // Don't close when hovering over the button (technically \"out\")\n if (event.relatedTarget && event.relatedTarget.classList.contains('vui-editor-insert-btn')) {\n return;\n }\n\n this.hide();\n }\n\n mousedownHandler() {\n this.preventHide = true;\n }\n\n focusHandler() {\n this.update(this.options.editor.view);\n }\n\n blurHandler(event) {\n if (this.preventHide) {\n this.preventHide = false;\n return;\n }\n\n this.hide(event);\n }\n\n resizeHandler() {\n if (this.isActive) {\n this.update(this.options.editor.view);\n }\n }\n\n isNodeEmpty($node) {\n const nodeJson = $node.toJSON();\n\n // Roll our own version of `isNodeEmpty` to handle text alignment and a few other cases.\n // We just check if the current node has no inner content.\n if (!nodeJson.content) {\n return true;\n }\n\n return false;\n }\n\n update(view, oldState) {\n const { state, composing } = view;\n const { doc, selection } = state;\n const isSame = oldState && oldState.doc.eq(doc) && oldState.selection.eq(selection);\n\n if (composing || isSame) {\n return;\n }\n\n const { $anchor, anchor, empty } = selection;\n const parent = this.options.element.offsetParent;\n const isRootDepth = $anchor.depth === 1;\n const isDefaultNodeType = $anchor.parent.type === state.doc.type.contentMatch.defaultType;\n const isDefaultNodeEmpty = this.isNodeEmpty(selection.$anchor.parent);\n const isActive = isRootDepth && isDefaultNodeType && isDefaultNodeEmpty;\n\n if (!empty || !parent || !isActive) {\n this.hide();\n\n return;\n }\n\n // Give it a sec for the UI to catch up with newly added blocks\n setTimeout(() => {\n const parentBox = parent.getBoundingClientRect();\n const cursorCoords = view.coordsAtPos(anchor);\n const top = cursorCoords.top - parentBox.top;\n\n this.isActive = true;\n this.top = top;\n\n this.sendUpdate();\n }, 10);\n }\n\n sendUpdate() {\n this.options.onUpdate({\n isActive: this.isActive,\n top: this.top,\n });\n }\n\n hide(event) {\n if (event && event.relatedTarget && this.options.element.parentNode && this.options.element.parentNode.contains(event.relatedTarget)) {\n return;\n }\n\n this.isActive = false;\n this.sendUpdate();\n }\n\n destroy() {\n if (this.behaviour === 'click') {\n this.options.element.removeEventListener('mousedown', this.mousedownHandler);\n this.options.editor.off('focus', this.focusHandler);\n this.options.editor.off('blur', this.blurHandler);\n this.options.editor.off('resize', this.resizeHandler);\n }\n\n if (this.behaviour === 'hover') {\n this.options.editor.view.dom.removeEventListener('mousemove', this.mouseenterHandler);\n this.options.editor.view.dom.removeEventListener('mouseleave', this.mouseleaveHandler);\n }\n }\n\n}\n\nexport default function(options) {\n return new Plugin({\n key: new PluginKey('floatingMenu'),\n view(editorView) {\n return new Menu({ editorView, options });\n },\n });\n}\n","\n","\n\n\n\n\n\n","// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/5/LICENSE\n\n// This is CodeMirror (https://codemirror.net/5), a code editor\n// implemented in JavaScript on top of the browser's DOM.\n//\n// You can find some technical background for some of the code below\n// at http://marijnhaverbeke.nl/blog/#cm-internals .\n\n(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :\n typeof define === 'function' && define.amd ? define(factory) :\n (global = global || self, global.CodeMirror = factory());\n}(this, (function () { 'use strict';\n\n // Kludges for bugs and behavior differences that can't be feature\n // detected are enabled based on userAgent etc sniffing.\n var userAgent = navigator.userAgent;\n var platform = navigator.platform;\n\n var gecko = /gecko\\/\\d/i.test(userAgent);\n var ie_upto10 = /MSIE \\d/.test(userAgent);\n var ie_11up = /Trident\\/(?:[7-9]|\\d{2,})\\..*rv:(\\d+)/.exec(userAgent);\n var edge = /Edge\\/(\\d+)/.exec(userAgent);\n var ie = ie_upto10 || ie_11up || edge;\n var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : +(edge || ie_11up)[1]);\n var webkit = !edge && /WebKit\\//.test(userAgent);\n var qtwebkit = webkit && /Qt\\/\\d+\\.\\d+/.test(userAgent);\n var chrome = !edge && /Chrome\\/(\\d+)/.exec(userAgent);\n var chrome_version = chrome && +chrome[1];\n var presto = /Opera\\//.test(userAgent);\n var safari = /Apple Computer/.test(navigator.vendor);\n var mac_geMountainLion = /Mac OS X 1\\d\\D([8-9]|\\d\\d)\\D/.test(userAgent);\n var phantom = /PhantomJS/.test(userAgent);\n\n var ios = safari && (/Mobile\\/\\w+/.test(userAgent) || navigator.maxTouchPoints > 2);\n var android = /Android/.test(userAgent);\n // This is woefully incomplete. Suggestions for alternative methods welcome.\n var mobile = ios || android || /webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent);\n var mac = ios || /Mac/.test(platform);\n var chromeOS = /\\bCrOS\\b/.test(userAgent);\n var windows = /win/i.test(platform);\n\n var presto_version = presto && userAgent.match(/Version\\/(\\d*\\.\\d*)/);\n if (presto_version) { presto_version = Number(presto_version[1]); }\n if (presto_version && presto_version >= 15) { presto = false; webkit = true; }\n // Some browsers use the wrong event properties to signal cmd/ctrl on OS X\n var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11));\n var captureRightClick = gecko || (ie && ie_version >= 9);\n\n function classTest(cls) { return new RegExp(\"(^|\\\\s)\" + cls + \"(?:$|\\\\s)\\\\s*\") }\n\n var rmClass = function(node, cls) {\n var current = node.className;\n var match = classTest(cls).exec(current);\n if (match) {\n var after = current.slice(match.index + match[0].length);\n node.className = current.slice(0, match.index) + (after ? match[1] + after : \"\");\n }\n };\n\n function removeChildren(e) {\n for (var count = e.childNodes.length; count > 0; --count)\n { e.removeChild(e.firstChild); }\n return e\n }\n\n function removeChildrenAndAdd(parent, e) {\n return removeChildren(parent).appendChild(e)\n }\n\n function elt(tag, content, className, style) {\n var e = document.createElement(tag);\n if (className) { e.className = className; }\n if (style) { e.style.cssText = style; }\n if (typeof content == \"string\") { e.appendChild(document.createTextNode(content)); }\n else if (content) { for (var i = 0; i < content.length; ++i) { e.appendChild(content[i]); } }\n return e\n }\n // wrapper for elt, which removes the elt from the accessibility tree\n function eltP(tag, content, className, style) {\n var e = elt(tag, content, className, style);\n e.setAttribute(\"role\", \"presentation\");\n return e\n }\n\n var range;\n if (document.createRange) { range = function(node, start, end, endNode) {\n var r = document.createRange();\n r.setEnd(endNode || node, end);\n r.setStart(node, start);\n return r\n }; }\n else { range = function(node, start, end) {\n var r = document.body.createTextRange();\n try { r.moveToElementText(node.parentNode); }\n catch(e) { return r }\n r.collapse(true);\n r.moveEnd(\"character\", end);\n r.moveStart(\"character\", start);\n return r\n }; }\n\n function contains(parent, child) {\n if (child.nodeType == 3) // Android browser always returns false when child is a textnode\n { child = child.parentNode; }\n if (parent.contains)\n { return parent.contains(child) }\n do {\n if (child.nodeType == 11) { child = child.host; }\n if (child == parent) { return true }\n } while (child = child.parentNode)\n }\n\n function activeElt(doc) {\n // IE and Edge may throw an \"Unspecified Error\" when accessing document.activeElement.\n // IE < 10 will throw when accessed while the page is loading or in an iframe.\n // IE > 9 and Edge will throw when accessed in an iframe if document.body is unavailable.\n var activeElement;\n try {\n activeElement = doc.activeElement;\n } catch(e) {\n activeElement = doc.body || null;\n }\n while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement)\n { activeElement = activeElement.shadowRoot.activeElement; }\n return activeElement\n }\n\n function addClass(node, cls) {\n var current = node.className;\n if (!classTest(cls).test(current)) { node.className += (current ? \" \" : \"\") + cls; }\n }\n function joinClasses(a, b) {\n var as = a.split(\" \");\n for (var i = 0; i < as.length; i++)\n { if (as[i] && !classTest(as[i]).test(b)) { b += \" \" + as[i]; } }\n return b\n }\n\n var selectInput = function(node) { node.select(); };\n if (ios) // Mobile Safari apparently has a bug where select() is broken.\n { selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; }; }\n else if (ie) // Suppress mysterious IE10 errors\n { selectInput = function(node) { try { node.select(); } catch(_e) {} }; }\n\n function doc(cm) { return cm.display.wrapper.ownerDocument }\n\n function win(cm) { return doc(cm).defaultView }\n\n function bind(f) {\n var args = Array.prototype.slice.call(arguments, 1);\n return function(){return f.apply(null, args)}\n }\n\n function copyObj(obj, target, overwrite) {\n if (!target) { target = {}; }\n for (var prop in obj)\n { if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))\n { target[prop] = obj[prop]; } }\n return target\n }\n\n // Counts the column offset in a string, taking tabs into account.\n // Used mostly to find indentation.\n function countColumn(string, end, tabSize, startIndex, startValue) {\n if (end == null) {\n end = string.search(/[^\\s\\u00a0]/);\n if (end == -1) { end = string.length; }\n }\n for (var i = startIndex || 0, n = startValue || 0;;) {\n var nextTab = string.indexOf(\"\\t\", i);\n if (nextTab < 0 || nextTab >= end)\n { return n + (end - i) }\n n += nextTab - i;\n n += tabSize - (n % tabSize);\n i = nextTab + 1;\n }\n }\n\n var Delayed = function() {\n this.id = null;\n this.f = null;\n this.time = 0;\n this.handler = bind(this.onTimeout, this);\n };\n Delayed.prototype.onTimeout = function (self) {\n self.id = 0;\n if (self.time <= +new Date) {\n self.f();\n } else {\n setTimeout(self.handler, self.time - +new Date);\n }\n };\n Delayed.prototype.set = function (ms, f) {\n this.f = f;\n var time = +new Date + ms;\n if (!this.id || time < this.time) {\n clearTimeout(this.id);\n this.id = setTimeout(this.handler, ms);\n this.time = time;\n }\n };\n\n function indexOf(array, elt) {\n for (var i = 0; i < array.length; ++i)\n { if (array[i] == elt) { return i } }\n return -1\n }\n\n // Number of pixels added to scroller and sizer to hide scrollbar\n var scrollerGap = 50;\n\n // Returned or thrown by various protocols to signal 'I'm not\n // handling this'.\n var Pass = {toString: function(){return \"CodeMirror.Pass\"}};\n\n // Reused option objects for setSelection & friends\n var sel_dontScroll = {scroll: false}, sel_mouse = {origin: \"*mouse\"}, sel_move = {origin: \"+move\"};\n\n // The inverse of countColumn -- find the offset that corresponds to\n // a particular column.\n function findColumn(string, goal, tabSize) {\n for (var pos = 0, col = 0;;) {\n var nextTab = string.indexOf(\"\\t\", pos);\n if (nextTab == -1) { nextTab = string.length; }\n var skipped = nextTab - pos;\n if (nextTab == string.length || col + skipped >= goal)\n { return pos + Math.min(skipped, goal - col) }\n col += nextTab - pos;\n col += tabSize - (col % tabSize);\n pos = nextTab + 1;\n if (col >= goal) { return pos }\n }\n }\n\n var spaceStrs = [\"\"];\n function spaceStr(n) {\n while (spaceStrs.length <= n)\n { spaceStrs.push(lst(spaceStrs) + \" \"); }\n return spaceStrs[n]\n }\n\n function lst(arr) { return arr[arr.length-1] }\n\n function map(array, f) {\n var out = [];\n for (var i = 0; i < array.length; i++) { out[i] = f(array[i], i); }\n return out\n }\n\n function insertSorted(array, value, score) {\n var pos = 0, priority = score(value);\n while (pos < array.length && score(array[pos]) <= priority) { pos++; }\n array.splice(pos, 0, value);\n }\n\n function nothing() {}\n\n function createObj(base, props) {\n var inst;\n if (Object.create) {\n inst = Object.create(base);\n } else {\n nothing.prototype = base;\n inst = new nothing();\n }\n if (props) { copyObj(props, inst); }\n return inst\n }\n\n var nonASCIISingleCaseWordChar = /[\\u00df\\u0587\\u0590-\\u05f4\\u0600-\\u06ff\\u3040-\\u309f\\u30a0-\\u30ff\\u3400-\\u4db5\\u4e00-\\u9fcc\\uac00-\\ud7af]/;\n function isWordCharBasic(ch) {\n return /\\w/.test(ch) || ch > \"\\x80\" &&\n (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch))\n }\n function isWordChar(ch, helper) {\n if (!helper) { return isWordCharBasic(ch) }\n if (helper.source.indexOf(\"\\\\w\") > -1 && isWordCharBasic(ch)) { return true }\n return helper.test(ch)\n }\n\n function isEmpty(obj) {\n for (var n in obj) { if (obj.hasOwnProperty(n) && obj[n]) { return false } }\n return true\n }\n\n // Extending unicode characters. A series of a non-extending char +\n // any number of extending chars is treated as a single unit as far\n // as editing and measuring is concerned. This is not fully correct,\n // since some scripts/fonts/browsers also treat other configurations\n // of code points as a group.\n var extendingChars = /[\\u0300-\\u036f\\u0483-\\u0489\\u0591-\\u05bd\\u05bf\\u05c1\\u05c2\\u05c4\\u05c5\\u05c7\\u0610-\\u061a\\u064b-\\u065e\\u0670\\u06d6-\\u06dc\\u06de-\\u06e4\\u06e7\\u06e8\\u06ea-\\u06ed\\u0711\\u0730-\\u074a\\u07a6-\\u07b0\\u07eb-\\u07f3\\u0816-\\u0819\\u081b-\\u0823\\u0825-\\u0827\\u0829-\\u082d\\u0900-\\u0902\\u093c\\u0941-\\u0948\\u094d\\u0951-\\u0955\\u0962\\u0963\\u0981\\u09bc\\u09be\\u09c1-\\u09c4\\u09cd\\u09d7\\u09e2\\u09e3\\u0a01\\u0a02\\u0a3c\\u0a41\\u0a42\\u0a47\\u0a48\\u0a4b-\\u0a4d\\u0a51\\u0a70\\u0a71\\u0a75\\u0a81\\u0a82\\u0abc\\u0ac1-\\u0ac5\\u0ac7\\u0ac8\\u0acd\\u0ae2\\u0ae3\\u0b01\\u0b3c\\u0b3e\\u0b3f\\u0b41-\\u0b44\\u0b4d\\u0b56\\u0b57\\u0b62\\u0b63\\u0b82\\u0bbe\\u0bc0\\u0bcd\\u0bd7\\u0c3e-\\u0c40\\u0c46-\\u0c48\\u0c4a-\\u0c4d\\u0c55\\u0c56\\u0c62\\u0c63\\u0cbc\\u0cbf\\u0cc2\\u0cc6\\u0ccc\\u0ccd\\u0cd5\\u0cd6\\u0ce2\\u0ce3\\u0d3e\\u0d41-\\u0d44\\u0d4d\\u0d57\\u0d62\\u0d63\\u0dca\\u0dcf\\u0dd2-\\u0dd4\\u0dd6\\u0ddf\\u0e31\\u0e34-\\u0e3a\\u0e47-\\u0e4e\\u0eb1\\u0eb4-\\u0eb9\\u0ebb\\u0ebc\\u0ec8-\\u0ecd\\u0f18\\u0f19\\u0f35\\u0f37\\u0f39\\u0f71-\\u0f7e\\u0f80-\\u0f84\\u0f86\\u0f87\\u0f90-\\u0f97\\u0f99-\\u0fbc\\u0fc6\\u102d-\\u1030\\u1032-\\u1037\\u1039\\u103a\\u103d\\u103e\\u1058\\u1059\\u105e-\\u1060\\u1071-\\u1074\\u1082\\u1085\\u1086\\u108d\\u109d\\u135f\\u1712-\\u1714\\u1732-\\u1734\\u1752\\u1753\\u1772\\u1773\\u17b7-\\u17bd\\u17c6\\u17c9-\\u17d3\\u17dd\\u180b-\\u180d\\u18a9\\u1920-\\u1922\\u1927\\u1928\\u1932\\u1939-\\u193b\\u1a17\\u1a18\\u1a56\\u1a58-\\u1a5e\\u1a60\\u1a62\\u1a65-\\u1a6c\\u1a73-\\u1a7c\\u1a7f\\u1b00-\\u1b03\\u1b34\\u1b36-\\u1b3a\\u1b3c\\u1b42\\u1b6b-\\u1b73\\u1b80\\u1b81\\u1ba2-\\u1ba5\\u1ba8\\u1ba9\\u1c2c-\\u1c33\\u1c36\\u1c37\\u1cd0-\\u1cd2\\u1cd4-\\u1ce0\\u1ce2-\\u1ce8\\u1ced\\u1dc0-\\u1de6\\u1dfd-\\u1dff\\u200c\\u200d\\u20d0-\\u20f0\\u2cef-\\u2cf1\\u2de0-\\u2dff\\u302a-\\u302f\\u3099\\u309a\\ua66f-\\ua672\\ua67c\\ua67d\\ua6f0\\ua6f1\\ua802\\ua806\\ua80b\\ua825\\ua826\\ua8c4\\ua8e0-\\ua8f1\\ua926-\\ua92d\\ua947-\\ua951\\ua980-\\ua982\\ua9b3\\ua9b6-\\ua9b9\\ua9bc\\uaa29-\\uaa2e\\uaa31\\uaa32\\uaa35\\uaa36\\uaa43\\uaa4c\\uaab0\\uaab2-\\uaab4\\uaab7\\uaab8\\uaabe\\uaabf\\uaac1\\uabe5\\uabe8\\uabed\\udc00-\\udfff\\ufb1e\\ufe00-\\ufe0f\\ufe20-\\ufe26\\uff9e\\uff9f]/;\n function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch) }\n\n // Returns a number from the range [`0`; `str.length`] unless `pos` is outside that range.\n function skipExtendingChars(str, pos, dir) {\n while ((dir < 0 ? pos > 0 : pos < str.length) && isExtendingChar(str.charAt(pos))) { pos += dir; }\n return pos\n }\n\n // Returns the value from the range [`from`; `to`] that satisfies\n // `pred` and is closest to `from`. Assumes that at least `to`\n // satisfies `pred`. Supports `from` being greater than `to`.\n function findFirst(pred, from, to) {\n // At any point we are certain `to` satisfies `pred`, don't know\n // whether `from` does.\n var dir = from > to ? -1 : 1;\n for (;;) {\n if (from == to) { return from }\n var midF = (from + to) / 2, mid = dir < 0 ? Math.ceil(midF) : Math.floor(midF);\n if (mid == from) { return pred(mid) ? from : to }\n if (pred(mid)) { to = mid; }\n else { from = mid + dir; }\n }\n }\n\n // BIDI HELPERS\n\n function iterateBidiSections(order, from, to, f) {\n if (!order) { return f(from, to, \"ltr\", 0) }\n var found = false;\n for (var i = 0; i < order.length; ++i) {\n var part = order[i];\n if (part.from < to && part.to > from || from == to && part.to == from) {\n f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? \"rtl\" : \"ltr\", i);\n found = true;\n }\n }\n if (!found) { f(from, to, \"ltr\"); }\n }\n\n var bidiOther = null;\n function getBidiPartAt(order, ch, sticky) {\n var found;\n bidiOther = null;\n for (var i = 0; i < order.length; ++i) {\n var cur = order[i];\n if (cur.from < ch && cur.to > ch) { return i }\n if (cur.to == ch) {\n if (cur.from != cur.to && sticky == \"before\") { found = i; }\n else { bidiOther = i; }\n }\n if (cur.from == ch) {\n if (cur.from != cur.to && sticky != \"before\") { found = i; }\n else { bidiOther = i; }\n }\n }\n return found != null ? found : bidiOther\n }\n\n // Bidirectional ordering algorithm\n // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm\n // that this (partially) implements.\n\n // One-char codes used for character types:\n // L (L): Left-to-Right\n // R (R): Right-to-Left\n // r (AL): Right-to-Left Arabic\n // 1 (EN): European Number\n // + (ES): European Number Separator\n // % (ET): European Number Terminator\n // n (AN): Arabic Number\n // , (CS): Common Number Separator\n // m (NSM): Non-Spacing Mark\n // b (BN): Boundary Neutral\n // s (B): Paragraph Separator\n // t (S): Segment Separator\n // w (WS): Whitespace\n // N (ON): Other Neutrals\n\n // Returns null if characters are ordered as they appear\n // (left-to-right), or an array of sections ({from, to, level}\n // objects) in the order in which they occur visually.\n var bidiOrdering = (function() {\n // Character types for codepoints 0 to 0xff\n var lowTypes = \"bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN\";\n // Character types for codepoints 0x600 to 0x6f9\n var arabicTypes = \"nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111\";\n function charType(code) {\n if (code <= 0xf7) { return lowTypes.charAt(code) }\n else if (0x590 <= code && code <= 0x5f4) { return \"R\" }\n else if (0x600 <= code && code <= 0x6f9) { return arabicTypes.charAt(code - 0x600) }\n else if (0x6ee <= code && code <= 0x8ac) { return \"r\" }\n else if (0x2000 <= code && code <= 0x200b) { return \"w\" }\n else if (code == 0x200c) { return \"b\" }\n else { return \"L\" }\n }\n\n var bidiRE = /[\\u0590-\\u05f4\\u0600-\\u06ff\\u0700-\\u08ac]/;\n var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;\n\n function BidiSpan(level, from, to) {\n this.level = level;\n this.from = from; this.to = to;\n }\n\n return function(str, direction) {\n var outerType = direction == \"ltr\" ? \"L\" : \"R\";\n\n if (str.length == 0 || direction == \"ltr\" && !bidiRE.test(str)) { return false }\n var len = str.length, types = [];\n for (var i = 0; i < len; ++i)\n { types.push(charType(str.charCodeAt(i))); }\n\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 for (var i$1 = 0, prev = outerType; i$1 < len; ++i$1) {\n var type = types[i$1];\n if (type == \"m\") { types[i$1] = prev; }\n else { prev = type; }\n }\n\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 for (var i$2 = 0, cur = outerType; i$2 < len; ++i$2) {\n var type$1 = types[i$2];\n if (type$1 == \"1\" && cur == \"r\") { types[i$2] = \"n\"; }\n else if (isStrong.test(type$1)) { cur = type$1; if (type$1 == \"r\") { types[i$2] = \"R\"; } }\n }\n\n // W4. A single European separator between two European numbers\n // changes to a European number. A single common separator between\n // two numbers of the same type changes to that type.\n for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) {\n var type$2 = types[i$3];\n if (type$2 == \"+\" && prev$1 == \"1\" && types[i$3+1] == \"1\") { types[i$3] = \"1\"; }\n else if (type$2 == \",\" && prev$1 == types[i$3+1] &&\n (prev$1 == \"1\" || prev$1 == \"n\")) { types[i$3] = prev$1; }\n prev$1 = type$2;\n }\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 for (var i$4 = 0; i$4 < len; ++i$4) {\n var type$3 = types[i$4];\n if (type$3 == \",\") { types[i$4] = \"N\"; }\n else if (type$3 == \"%\") {\n var end = (void 0);\n for (end = i$4 + 1; end < len && types[end] == \"%\"; ++end) {}\n var replace = (i$4 && types[i$4-1] == \"!\") || (end < len && types[end] == \"1\") ? \"1\" : \"N\";\n for (var j = i$4; j < end; ++j) { types[j] = replace; }\n i$4 = end - 1;\n }\n }\n\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 for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) {\n var type$4 = types[i$5];\n if (cur$1 == \"L\" && type$4 == \"1\") { types[i$5] = \"L\"; }\n else if (isStrong.test(type$4)) { cur$1 = type$4; }\n }\n\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 for (var i$6 = 0; i$6 < len; ++i$6) {\n if (isNeutral.test(types[i$6])) {\n var end$1 = (void 0);\n for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]); ++end$1) {}\n var before = (i$6 ? types[i$6-1] : outerType) == \"L\";\n var after = (end$1 < len ? types[end$1] : outerType) == \"L\";\n var replace$1 = before == after ? (before ? \"L\" : \"R\") : outerType;\n for (var j$1 = i$6; j$1 < end$1; ++j$1) { types[j$1] = replace$1; }\n i$6 = end$1 - 1;\n }\n }\n\n // Here we depart from the documented algorithm, in order to avoid\n // building up an actual levels array. Since there are only three\n // levels (0, 1, 2) in an implementation that doesn't take\n // explicit embedding into account, we can build up the order on\n // the fly, without following the level-based algorithm.\n var order = [], m;\n for (var i$7 = 0; i$7 < len;) {\n if (countsAsLeft.test(types[i$7])) {\n var start = i$7;\n for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]); ++i$7) {}\n order.push(new BidiSpan(0, start, i$7));\n } else {\n var pos = i$7, at = order.length, isRTL = direction == \"rtl\" ? 1 : 0;\n for (++i$7; i$7 < len && types[i$7] != \"L\"; ++i$7) {}\n for (var j$2 = pos; j$2 < i$7;) {\n if (countsAsNum.test(types[j$2])) {\n if (pos < j$2) { order.splice(at, 0, new BidiSpan(1, pos, j$2)); at += isRTL; }\n var nstart = j$2;\n for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]); ++j$2) {}\n order.splice(at, 0, new BidiSpan(2, nstart, j$2));\n at += isRTL;\n pos = j$2;\n } else { ++j$2; }\n }\n if (pos < i$7) { order.splice(at, 0, new BidiSpan(1, pos, i$7)); }\n }\n }\n if (direction == \"ltr\") {\n if (order[0].level == 1 && (m = str.match(/^\\s+/))) {\n order[0].from = m[0].length;\n order.unshift(new BidiSpan(0, 0, m[0].length));\n }\n if (lst(order).level == 1 && (m = str.match(/\\s+$/))) {\n lst(order).to -= m[0].length;\n order.push(new BidiSpan(0, len - m[0].length, len));\n }\n }\n\n return direction == \"rtl\" ? order.reverse() : order\n }\n })();\n\n // Get the bidi ordering for the given line (and cache it). Returns\n // false for lines that are fully left-to-right, and an array of\n // BidiSpan objects otherwise.\n function getOrder(line, direction) {\n var order = line.order;\n if (order == null) { order = line.order = bidiOrdering(line.text, direction); }\n return order\n }\n\n // EVENT HANDLING\n\n // Lightweight event framework. on/off also work on DOM nodes,\n // registering native DOM handlers.\n\n var noHandlers = [];\n\n var on = function(emitter, type, f) {\n if (emitter.addEventListener) {\n emitter.addEventListener(type, f, false);\n } else if (emitter.attachEvent) {\n emitter.attachEvent(\"on\" + type, f);\n } else {\n var map = emitter._handlers || (emitter._handlers = {});\n map[type] = (map[type] || noHandlers).concat(f);\n }\n };\n\n function getHandlers(emitter, type) {\n return emitter._handlers && emitter._handlers[type] || noHandlers\n }\n\n function off(emitter, type, f) {\n if (emitter.removeEventListener) {\n emitter.removeEventListener(type, f, false);\n } else if (emitter.detachEvent) {\n emitter.detachEvent(\"on\" + type, f);\n } else {\n var map = emitter._handlers, arr = map && map[type];\n if (arr) {\n var index = indexOf(arr, f);\n if (index > -1)\n { map[type] = arr.slice(0, index).concat(arr.slice(index + 1)); }\n }\n }\n }\n\n function signal(emitter, type /*, values...*/) {\n var handlers = getHandlers(emitter, type);\n if (!handlers.length) { return }\n var args = Array.prototype.slice.call(arguments, 2);\n for (var i = 0; i < handlers.length; ++i) { handlers[i].apply(null, args); }\n }\n\n // The DOM events that CodeMirror handles can be overridden by\n // registering a (non-DOM) handler on the editor for the event name,\n // and preventDefault-ing the event in that handler.\n function signalDOMEvent(cm, e, override) {\n if (typeof e == \"string\")\n { e = {type: e, preventDefault: function() { this.defaultPrevented = true; }}; }\n signal(cm, override || e.type, cm, e);\n return e_defaultPrevented(e) || e.codemirrorIgnore\n }\n\n function signalCursorActivity(cm) {\n var arr = cm._handlers && cm._handlers.cursorActivity;\n if (!arr) { return }\n var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);\n for (var i = 0; i < arr.length; ++i) { if (indexOf(set, arr[i]) == -1)\n { set.push(arr[i]); } }\n }\n\n function hasHandler(emitter, type) {\n return getHandlers(emitter, type).length > 0\n }\n\n // Add on and off methods to a constructor's prototype, to make\n // registering events on such objects more convenient.\n function eventMixin(ctor) {\n ctor.prototype.on = function(type, f) {on(this, type, f);};\n ctor.prototype.off = function(type, f) {off(this, type, f);};\n }\n\n // Due to the fact that we still support jurassic IE versions, some\n // compatibility wrappers are needed.\n\n function e_preventDefault(e) {\n if (e.preventDefault) { e.preventDefault(); }\n else { e.returnValue = false; }\n }\n function e_stopPropagation(e) {\n if (e.stopPropagation) { e.stopPropagation(); }\n else { e.cancelBubble = true; }\n }\n function e_defaultPrevented(e) {\n return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false\n }\n function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);}\n\n function e_target(e) {return e.target || e.srcElement}\n function e_button(e) {\n var b = e.which;\n if (b == null) {\n if (e.button & 1) { b = 1; }\n else if (e.button & 2) { b = 3; }\n else if (e.button & 4) { b = 2; }\n }\n if (mac && e.ctrlKey && b == 1) { b = 3; }\n return b\n }\n\n // Detect drag-and-drop\n var dragAndDrop = function() {\n // There is *some* kind of drag-and-drop support in IE6-8, but I\n // couldn't get it to work yet.\n if (ie && ie_version < 9) { return false }\n var div = elt('div');\n return \"draggable\" in div || \"dragDrop\" in div\n }();\n\n var zwspSupported;\n function zeroWidthElement(measure) {\n if (zwspSupported == null) {\n var test = elt(\"span\", \"\\u200b\");\n removeChildrenAndAdd(measure, elt(\"span\", [test, document.createTextNode(\"x\")]));\n if (measure.firstChild.offsetHeight != 0)\n { zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8); }\n }\n var node = zwspSupported ? elt(\"span\", \"\\u200b\") :\n elt(\"span\", \"\\u00a0\", null, \"display: inline-block; width: 1px; margin-right: -1px\");\n node.setAttribute(\"cm-text\", \"\");\n return node\n }\n\n // Feature-detect IE's crummy client rect reporting for bidi text\n var badBidiRects;\n function hasBadBidiRects(measure) {\n if (badBidiRects != null) { return badBidiRects }\n var txt = removeChildrenAndAdd(measure, document.createTextNode(\"A\\u062eA\"));\n var r0 = range(txt, 0, 1).getBoundingClientRect();\n var r1 = range(txt, 1, 2).getBoundingClientRect();\n removeChildren(measure);\n if (!r0 || r0.left == r0.right) { return false } // Safari returns null in some cases (#2780)\n return badBidiRects = (r1.right - r0.right < 3)\n }\n\n // See if \"\".split is the broken IE version, if so, provide an\n // alternative way to split lines.\n var splitLinesAuto = \"\\n\\nb\".split(/\\n/).length != 3 ? function (string) {\n var pos = 0, result = [], l = string.length;\n while (pos <= l) {\n var nl = string.indexOf(\"\\n\", pos);\n if (nl == -1) { nl = string.length; }\n var line = string.slice(pos, string.charAt(nl - 1) == \"\\r\" ? nl - 1 : nl);\n var rt = line.indexOf(\"\\r\");\n if (rt != -1) {\n result.push(line.slice(0, rt));\n pos += rt + 1;\n } else {\n result.push(line);\n pos = nl + 1;\n }\n }\n return result\n } : function (string) { return string.split(/\\r\\n?|\\n/); };\n\n var hasSelection = window.getSelection ? function (te) {\n try { return te.selectionStart != te.selectionEnd }\n catch(e) { return false }\n } : function (te) {\n var range;\n try {range = te.ownerDocument.selection.createRange();}\n catch(e) {}\n if (!range || range.parentElement() != te) { return false }\n return range.compareEndPoints(\"StartToEnd\", range) != 0\n };\n\n var hasCopyEvent = (function () {\n var e = elt(\"div\");\n if (\"oncopy\" in e) { return true }\n e.setAttribute(\"oncopy\", \"return;\");\n return typeof e.oncopy == \"function\"\n })();\n\n var badZoomedRects = null;\n function hasBadZoomedRects(measure) {\n if (badZoomedRects != null) { return badZoomedRects }\n var node = removeChildrenAndAdd(measure, elt(\"span\", \"x\"));\n var normal = node.getBoundingClientRect();\n var fromRange = range(node, 0, 1).getBoundingClientRect();\n return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1\n }\n\n // Known modes, by name and by MIME\n var modes = {}, mimeModes = {};\n\n // Extra arguments are stored as the mode's dependencies, which is\n // used by (legacy) mechanisms like loadmode.js to automatically\n // load a mode. (Preferred mechanism is the require/define calls.)\n function defineMode(name, mode) {\n if (arguments.length > 2)\n { mode.dependencies = Array.prototype.slice.call(arguments, 2); }\n modes[name] = mode;\n }\n\n function defineMIME(mime, spec) {\n mimeModes[mime] = spec;\n }\n\n // Given a MIME type, a {name, ...options} config object, or a name\n // string, return a mode config object.\n function resolveMode(spec) {\n if (typeof spec == \"string\" && mimeModes.hasOwnProperty(spec)) {\n spec = mimeModes[spec];\n } else if (spec && typeof spec.name == \"string\" && mimeModes.hasOwnProperty(spec.name)) {\n var found = mimeModes[spec.name];\n if (typeof found == \"string\") { found = {name: found}; }\n spec = createObj(found, spec);\n spec.name = found.name;\n } else if (typeof spec == \"string\" && /^[\\w\\-]+\\/[\\w\\-]+\\+xml$/.test(spec)) {\n return resolveMode(\"application/xml\")\n } else if (typeof spec == \"string\" && /^[\\w\\-]+\\/[\\w\\-]+\\+json$/.test(spec)) {\n return resolveMode(\"application/json\")\n }\n if (typeof spec == \"string\") { return {name: spec} }\n else { return spec || {name: \"null\"} }\n }\n\n // Given a mode spec (anything that resolveMode accepts), find and\n // initialize an actual mode object.\n function getMode(options, spec) {\n spec = resolveMode(spec);\n var mfactory = modes[spec.name];\n if (!mfactory) { return getMode(options, \"text/plain\") }\n var modeObj = mfactory(options, spec);\n if (modeExtensions.hasOwnProperty(spec.name)) {\n var exts = modeExtensions[spec.name];\n for (var prop in exts) {\n if (!exts.hasOwnProperty(prop)) { continue }\n if (modeObj.hasOwnProperty(prop)) { modeObj[\"_\" + prop] = modeObj[prop]; }\n modeObj[prop] = exts[prop];\n }\n }\n modeObj.name = spec.name;\n if (spec.helperType) { modeObj.helperType = spec.helperType; }\n if (spec.modeProps) { for (var prop$1 in spec.modeProps)\n { modeObj[prop$1] = spec.modeProps[prop$1]; } }\n\n return modeObj\n }\n\n // This can be used to attach properties to mode objects from\n // outside the actual mode definition.\n var modeExtensions = {};\n function extendMode(mode, properties) {\n var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});\n copyObj(properties, exts);\n }\n\n function copyState(mode, state) {\n if (state === true) { return state }\n if (mode.copyState) { return mode.copyState(state) }\n var nstate = {};\n for (var n in state) {\n var val = state[n];\n if (val instanceof Array) { val = val.concat([]); }\n nstate[n] = val;\n }\n return nstate\n }\n\n // Given a mode and a state (for that mode), find the inner mode and\n // state at the position that the state refers to.\n function innerMode(mode, state) {\n var info;\n while (mode.innerMode) {\n info = mode.innerMode(state);\n if (!info || info.mode == mode) { break }\n state = info.state;\n mode = info.mode;\n }\n return info || {mode: mode, state: state}\n }\n\n function startState(mode, a1, a2) {\n return mode.startState ? mode.startState(a1, a2) : true\n }\n\n // STRING STREAM\n\n // Fed to the mode parsers, provides helper functions to make\n // parsers more succinct.\n\n var StringStream = function(string, tabSize, lineOracle) {\n this.pos = this.start = 0;\n this.string = string;\n this.tabSize = tabSize || 8;\n this.lastColumnPos = this.lastColumnValue = 0;\n this.lineStart = 0;\n this.lineOracle = lineOracle;\n };\n\n StringStream.prototype.eol = function () {return this.pos >= this.string.length};\n StringStream.prototype.sol = function () {return this.pos == this.lineStart};\n StringStream.prototype.peek = function () {return this.string.charAt(this.pos) || undefined};\n StringStream.prototype.next = function () {\n if (this.pos < this.string.length)\n { return this.string.charAt(this.pos++) }\n };\n StringStream.prototype.eat = function (match) {\n var ch = this.string.charAt(this.pos);\n var ok;\n if (typeof match == \"string\") { ok = ch == match; }\n else { ok = ch && (match.test ? match.test(ch) : match(ch)); }\n if (ok) {++this.pos; return ch}\n };\n StringStream.prototype.eatWhile = function (match) {\n var start = this.pos;\n while (this.eat(match)){}\n return this.pos > start\n };\n StringStream.prototype.eatSpace = function () {\n var start = this.pos;\n while (/[\\s\\u00a0]/.test(this.string.charAt(this.pos))) { ++this.pos; }\n return this.pos > start\n };\n StringStream.prototype.skipToEnd = function () {this.pos = this.string.length;};\n StringStream.prototype.skipTo = function (ch) {\n var found = this.string.indexOf(ch, this.pos);\n if (found > -1) {this.pos = found; return true}\n };\n StringStream.prototype.backUp = function (n) {this.pos -= n;};\n StringStream.prototype.column = function () {\n if (this.lastColumnPos < this.start) {\n this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);\n this.lastColumnPos = this.start;\n }\n return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)\n };\n StringStream.prototype.indentation = function () {\n return countColumn(this.string, null, this.tabSize) -\n (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)\n };\n StringStream.prototype.match = function (pattern, consume, caseInsensitive) {\n if (typeof pattern == \"string\") {\n var cased = function (str) { return caseInsensitive ? str.toLowerCase() : str; };\n var substr = this.string.substr(this.pos, pattern.length);\n if (cased(substr) == cased(pattern)) {\n if (consume !== false) { this.pos += pattern.length; }\n return true\n }\n } else {\n var match = this.string.slice(this.pos).match(pattern);\n if (match && match.index > 0) { return null }\n if (match && consume !== false) { this.pos += match[0].length; }\n return match\n }\n };\n StringStream.prototype.current = function (){return this.string.slice(this.start, this.pos)};\n StringStream.prototype.hideFirstChars = function (n, inner) {\n this.lineStart += n;\n try { return inner() }\n finally { this.lineStart -= n; }\n };\n StringStream.prototype.lookAhead = function (n) {\n var oracle = this.lineOracle;\n return oracle && oracle.lookAhead(n)\n };\n StringStream.prototype.baseToken = function () {\n var oracle = this.lineOracle;\n return oracle && oracle.baseToken(this.pos)\n };\n\n // Find the line object corresponding to the given line number.\n function getLine(doc, n) {\n n -= doc.first;\n if (n < 0 || n >= doc.size) { throw new Error(\"There is no line \" + (n + doc.first) + \" in the document.\") }\n var chunk = doc;\n while (!chunk.lines) {\n for (var i = 0;; ++i) {\n var child = chunk.children[i], sz = child.chunkSize();\n if (n < sz) { chunk = child; break }\n n -= sz;\n }\n }\n return chunk.lines[n]\n }\n\n // Get the part of a document between two positions, as an array of\n // strings.\n function getBetween(doc, start, end) {\n var out = [], n = start.line;\n doc.iter(start.line, end.line + 1, function (line) {\n var text = line.text;\n if (n == end.line) { text = text.slice(0, end.ch); }\n if (n == start.line) { text = text.slice(start.ch); }\n out.push(text);\n ++n;\n });\n return out\n }\n // Get the lines between from and to, as array of strings.\n function getLines(doc, from, to) {\n var out = [];\n doc.iter(from, to, function (line) { out.push(line.text); }); // iter aborts when callback returns truthy value\n return out\n }\n\n // Update the height of a line, propagating the height change\n // upwards to parent nodes.\n function updateLineHeight(line, height) {\n var diff = height - line.height;\n if (diff) { for (var n = line; n; n = n.parent) { n.height += diff; } }\n }\n\n // Given a line object, find its line number by walking up through\n // its parent links.\n function lineNo(line) {\n if (line.parent == null) { return null }\n var cur = line.parent, no = indexOf(cur.lines, line);\n for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {\n for (var i = 0;; ++i) {\n if (chunk.children[i] == cur) { break }\n no += chunk.children[i].chunkSize();\n }\n }\n return no + cur.first\n }\n\n // Find the line at the given vertical position, using the height\n // information in the document tree.\n function lineAtHeight(chunk, h) {\n var n = chunk.first;\n outer: do {\n for (var i$1 = 0; i$1 < chunk.children.length; ++i$1) {\n var child = chunk.children[i$1], ch = child.height;\n if (h < ch) { chunk = child; continue outer }\n h -= ch;\n n += child.chunkSize();\n }\n return n\n } while (!chunk.lines)\n var i = 0;\n for (; i < chunk.lines.length; ++i) {\n var line = chunk.lines[i], lh = line.height;\n if (h < lh) { break }\n h -= lh;\n }\n return n + i\n }\n\n function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size}\n\n function lineNumberFor(options, i) {\n return String(options.lineNumberFormatter(i + options.firstLineNumber))\n }\n\n // A Pos instance represents a position within the text.\n function Pos(line, ch, sticky) {\n if ( sticky === void 0 ) sticky = null;\n\n if (!(this instanceof Pos)) { return new Pos(line, ch, sticky) }\n this.line = line;\n this.ch = ch;\n this.sticky = sticky;\n }\n\n // Compare two positions, return 0 if they are the same, a negative\n // number when a is less, and a positive number otherwise.\n function cmp(a, b) { return a.line - b.line || a.ch - b.ch }\n\n function equalCursorPos(a, b) { return a.sticky == b.sticky && cmp(a, b) == 0 }\n\n function copyPos(x) {return Pos(x.line, x.ch)}\n function maxPos(a, b) { return cmp(a, b) < 0 ? b : a }\n function minPos(a, b) { return cmp(a, b) < 0 ? a : b }\n\n // Most of the external API clips given positions to make sure they\n // actually exist within the document.\n function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1))}\n function clipPos(doc, pos) {\n if (pos.line < doc.first) { return Pos(doc.first, 0) }\n var last = doc.first + doc.size - 1;\n if (pos.line > last) { return Pos(last, getLine(doc, last).text.length) }\n return clipToLen(pos, getLine(doc, pos.line).text.length)\n }\n function clipToLen(pos, linelen) {\n var ch = pos.ch;\n if (ch == null || ch > linelen) { return Pos(pos.line, linelen) }\n else if (ch < 0) { return Pos(pos.line, 0) }\n else { return pos }\n }\n function clipPosArray(doc, array) {\n var out = [];\n for (var i = 0; i < array.length; i++) { out[i] = clipPos(doc, array[i]); }\n return out\n }\n\n var SavedContext = function(state, lookAhead) {\n this.state = state;\n this.lookAhead = lookAhead;\n };\n\n var Context = function(doc, state, line, lookAhead) {\n this.state = state;\n this.doc = doc;\n this.line = line;\n this.maxLookAhead = lookAhead || 0;\n this.baseTokens = null;\n this.baseTokenPos = 1;\n };\n\n Context.prototype.lookAhead = function (n) {\n var line = this.doc.getLine(this.line + n);\n if (line != null && n > this.maxLookAhead) { this.maxLookAhead = n; }\n return line\n };\n\n Context.prototype.baseToken = function (n) {\n if (!this.baseTokens) { return null }\n while (this.baseTokens[this.baseTokenPos] <= n)\n { this.baseTokenPos += 2; }\n var type = this.baseTokens[this.baseTokenPos + 1];\n return {type: type && type.replace(/( |^)overlay .*/, \"\"),\n size: this.baseTokens[this.baseTokenPos] - n}\n };\n\n Context.prototype.nextLine = function () {\n this.line++;\n if (this.maxLookAhead > 0) { this.maxLookAhead--; }\n };\n\n Context.fromSaved = function (doc, saved, line) {\n if (saved instanceof SavedContext)\n { return new Context(doc, copyState(doc.mode, saved.state), line, saved.lookAhead) }\n else\n { return new Context(doc, copyState(doc.mode, saved), line) }\n };\n\n Context.prototype.save = function (copy) {\n var state = copy !== false ? copyState(this.doc.mode, this.state) : this.state;\n return this.maxLookAhead > 0 ? new SavedContext(state, this.maxLookAhead) : state\n };\n\n\n // Compute a style array (an array starting with a mode generation\n // -- for invalidation -- followed by pairs of end positions and\n // style strings), which is used to highlight the tokens on the\n // line.\n function highlightLine(cm, line, context, forceToEnd) {\n // A styles array always starts with a number identifying the\n // mode/overlays that it is based on (for easy invalidation).\n var st = [cm.state.modeGen], lineClasses = {};\n // Compute the base array of styles\n runMode(cm, line.text, cm.doc.mode, context, function (end, style) { return st.push(end, style); },\n lineClasses, forceToEnd);\n var state = context.state;\n\n // Run overlays, adjust style array.\n var loop = function ( o ) {\n context.baseTokens = st;\n var overlay = cm.state.overlays[o], i = 1, at = 0;\n context.state = true;\n runMode(cm, line.text, overlay.mode, context, function (end, style) {\n var start = i;\n // Ensure there's a token end at the current position, and that i points at it\n while (at < end) {\n var i_end = st[i];\n if (i_end > end)\n { st.splice(i, 1, end, st[i+1], i_end); }\n i += 2;\n at = Math.min(end, i_end);\n }\n if (!style) { return }\n if (overlay.opaque) {\n st.splice(start, i - start, end, \"overlay \" + style);\n i = start + 2;\n } else {\n for (; start < i; start += 2) {\n var cur = st[start+1];\n st[start+1] = (cur ? cur + \" \" : \"\") + \"overlay \" + style;\n }\n }\n }, lineClasses);\n context.state = state;\n context.baseTokens = null;\n context.baseTokenPos = 1;\n };\n\n for (var o = 0; o < cm.state.overlays.length; ++o) loop( o );\n\n return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null}\n }\n\n function getLineStyles(cm, line, updateFrontier) {\n if (!line.styles || line.styles[0] != cm.state.modeGen) {\n var context = getContextBefore(cm, lineNo(line));\n var resetState = line.text.length > cm.options.maxHighlightLength && copyState(cm.doc.mode, context.state);\n var result = highlightLine(cm, line, context);\n if (resetState) { context.state = resetState; }\n line.stateAfter = context.save(!resetState);\n line.styles = result.styles;\n if (result.classes) { line.styleClasses = result.classes; }\n else if (line.styleClasses) { line.styleClasses = null; }\n if (updateFrontier === cm.doc.highlightFrontier)\n { cm.doc.modeFrontier = Math.max(cm.doc.modeFrontier, ++cm.doc.highlightFrontier); }\n }\n return line.styles\n }\n\n function getContextBefore(cm, n, precise) {\n var doc = cm.doc, display = cm.display;\n if (!doc.mode.startState) { return new Context(doc, true, n) }\n var start = findStartLine(cm, n, precise);\n var saved = start > doc.first && getLine(doc, start - 1).stateAfter;\n var context = saved ? Context.fromSaved(doc, saved, start) : new Context(doc, startState(doc.mode), start);\n\n doc.iter(start, n, function (line) {\n processLine(cm, line.text, context);\n var pos = context.line;\n line.stateAfter = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo ? context.save() : null;\n context.nextLine();\n });\n if (precise) { doc.modeFrontier = context.line; }\n return context\n }\n\n // Lightweight form of highlight -- proceed over this line and\n // update state, but don't save a style array. Used for lines that\n // aren't currently visible.\n function processLine(cm, text, context, startAt) {\n var mode = cm.doc.mode;\n var stream = new StringStream(text, cm.options.tabSize, context);\n stream.start = stream.pos = startAt || 0;\n if (text == \"\") { callBlankLine(mode, context.state); }\n while (!stream.eol()) {\n readToken(mode, stream, context.state);\n stream.start = stream.pos;\n }\n }\n\n function callBlankLine(mode, state) {\n if (mode.blankLine) { return mode.blankLine(state) }\n if (!mode.innerMode) { return }\n var inner = innerMode(mode, state);\n if (inner.mode.blankLine) { return inner.mode.blankLine(inner.state) }\n }\n\n function readToken(mode, stream, state, inner) {\n for (var i = 0; i < 10; i++) {\n if (inner) { inner[0] = innerMode(mode, state).mode; }\n var style = mode.token(stream, state);\n if (stream.pos > stream.start) { return style }\n }\n throw new Error(\"Mode \" + mode.name + \" failed to advance stream.\")\n }\n\n var Token = function(stream, type, state) {\n this.start = stream.start; this.end = stream.pos;\n this.string = stream.current();\n this.type = type || null;\n this.state = state;\n };\n\n // Utility for getTokenAt and getLineTokens\n function takeToken(cm, pos, precise, asArray) {\n var doc = cm.doc, mode = doc.mode, style;\n pos = clipPos(doc, pos);\n var line = getLine(doc, pos.line), context = getContextBefore(cm, pos.line, precise);\n var stream = new StringStream(line.text, cm.options.tabSize, context), tokens;\n if (asArray) { tokens = []; }\n while ((asArray || stream.pos < pos.ch) && !stream.eol()) {\n stream.start = stream.pos;\n style = readToken(mode, stream, context.state);\n if (asArray) { tokens.push(new Token(stream, style, copyState(doc.mode, context.state))); }\n }\n return asArray ? tokens : new Token(stream, style, context.state)\n }\n\n function extractLineClasses(type, output) {\n if (type) { for (;;) {\n var lineClass = type.match(/(?:^|\\s+)line-(background-)?(\\S+)/);\n if (!lineClass) { break }\n type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length);\n var prop = lineClass[1] ? \"bgClass\" : \"textClass\";\n if (output[prop] == null)\n { output[prop] = lineClass[2]; }\n else if (!(new RegExp(\"(?:^|\\\\s)\" + lineClass[2] + \"(?:$|\\\\s)\")).test(output[prop]))\n { output[prop] += \" \" + lineClass[2]; }\n } }\n return type\n }\n\n // Run the given mode's parser over a line, calling f for each token.\n function runMode(cm, text, mode, context, f, lineClasses, forceToEnd) {\n var flattenSpans = mode.flattenSpans;\n if (flattenSpans == null) { flattenSpans = cm.options.flattenSpans; }\n var curStart = 0, curStyle = null;\n var stream = new StringStream(text, cm.options.tabSize, context), style;\n var inner = cm.options.addModeClass && [null];\n if (text == \"\") { extractLineClasses(callBlankLine(mode, context.state), lineClasses); }\n while (!stream.eol()) {\n if (stream.pos > cm.options.maxHighlightLength) {\n flattenSpans = false;\n if (forceToEnd) { processLine(cm, text, context, stream.pos); }\n stream.pos = text.length;\n style = null;\n } else {\n style = extractLineClasses(readToken(mode, stream, context.state, inner), lineClasses);\n }\n if (inner) {\n var mName = inner[0].name;\n if (mName) { style = \"m-\" + (style ? mName + \" \" + style : mName); }\n }\n if (!flattenSpans || curStyle != style) {\n while (curStart < stream.start) {\n curStart = Math.min(stream.start, curStart + 5000);\n f(curStart, curStyle);\n }\n curStyle = style;\n }\n stream.start = stream.pos;\n }\n while (curStart < stream.pos) {\n // Webkit seems to refuse to render text nodes longer than 57444\n // characters, and returns inaccurate measurements in nodes\n // starting around 5000 chars.\n var pos = Math.min(stream.pos, curStart + 5000);\n f(pos, curStyle);\n curStart = pos;\n }\n }\n\n // Finds the line to start with when starting a parse. Tries to\n // find a line with a stateAfter, so that it can start with a\n // valid state. If that fails, it returns the line with the\n // smallest indentation, which tends to need the least context to\n // parse correctly.\n function findStartLine(cm, n, precise) {\n var minindent, minline, doc = cm.doc;\n var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100);\n for (var search = n; search > lim; --search) {\n if (search <= doc.first) { return doc.first }\n var line = getLine(doc, search - 1), after = line.stateAfter;\n if (after && (!precise || search + (after instanceof SavedContext ? after.lookAhead : 0) <= doc.modeFrontier))\n { return search }\n var indented = countColumn(line.text, null, cm.options.tabSize);\n if (minline == null || minindent > indented) {\n minline = search - 1;\n minindent = indented;\n }\n }\n return minline\n }\n\n function retreatFrontier(doc, n) {\n doc.modeFrontier = Math.min(doc.modeFrontier, n);\n if (doc.highlightFrontier < n - 10) { return }\n var start = doc.first;\n for (var line = n - 1; line > start; line--) {\n var saved = getLine(doc, line).stateAfter;\n // change is on 3\n // state on line 1 looked ahead 2 -- so saw 3\n // test 1 + 2 < 3 should cover this\n if (saved && (!(saved instanceof SavedContext) || line + saved.lookAhead < n)) {\n start = line + 1;\n break\n }\n }\n doc.highlightFrontier = Math.min(doc.highlightFrontier, start);\n }\n\n // Optimize some code when these features are not used.\n var sawReadOnlySpans = false, sawCollapsedSpans = false;\n\n function seeReadOnlySpans() {\n sawReadOnlySpans = true;\n }\n\n function seeCollapsedSpans() {\n sawCollapsedSpans = true;\n }\n\n // TEXTMARKER SPANS\n\n function MarkedSpan(marker, from, to) {\n this.marker = marker;\n this.from = from; this.to = to;\n }\n\n // Search an array of spans for a span matching the given marker.\n function getMarkedSpanFor(spans, marker) {\n if (spans) { for (var i = 0; i < spans.length; ++i) {\n var span = spans[i];\n if (span.marker == marker) { return span }\n } }\n }\n\n // Remove a span from an array, returning undefined if no spans are\n // left (we don't store arrays for lines without spans).\n function removeMarkedSpan(spans, span) {\n var r;\n for (var i = 0; i < spans.length; ++i)\n { if (spans[i] != span) { (r || (r = [])).push(spans[i]); } }\n return r\n }\n\n // Add a span to a line.\n function addMarkedSpan(line, span, op) {\n var inThisOp = op && window.WeakSet && (op.markedSpans || (op.markedSpans = new WeakSet));\n if (inThisOp && line.markedSpans && inThisOp.has(line.markedSpans)) {\n line.markedSpans.push(span);\n } else {\n line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];\n if (inThisOp) { inThisOp.add(line.markedSpans); }\n }\n span.marker.attachLine(line);\n }\n\n // Used for the algorithm that adjusts markers for a change in the\n // document. These functions cut an array of spans at a given\n // character position, returning an array of remaining chunks (or\n // undefined if nothing remains).\n function markedSpansBefore(old, startCh, isInsert) {\n var nw;\n if (old) { for (var i = 0; i < old.length; ++i) {\n var span = old[i], marker = span.marker;\n var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);\n if (startsBefore || span.from == startCh && marker.type == \"bookmark\" && (!isInsert || !span.marker.insertLeft)) {\n var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh)\n ;(nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to));\n }\n } }\n return nw\n }\n function markedSpansAfter(old, endCh, isInsert) {\n var nw;\n if (old) { for (var i = 0; i < old.length; ++i) {\n var span = old[i], marker = span.marker;\n var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);\n if (endsAfter || span.from == endCh && marker.type == \"bookmark\" && (!isInsert || span.marker.insertLeft)) {\n var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh)\n ;(nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,\n span.to == null ? null : span.to - endCh));\n }\n } }\n return nw\n }\n\n // Given a change object, compute the new set of marker spans that\n // cover the line in which the change took place. Removes spans\n // entirely within the change, reconnects spans belonging to the\n // same marker that appear on both sides of the change, and cuts off\n // spans partially within the change. Returns an array of span\n // arrays with one element for each line in (after) the change.\n function stretchSpansOverChange(doc, change) {\n if (change.full) { return null }\n var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;\n var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;\n if (!oldFirst && !oldLast) { return null }\n\n var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;\n // Get the spans that 'stick out' on both sides\n var first = markedSpansBefore(oldFirst, startCh, isInsert);\n var last = markedSpansAfter(oldLast, endCh, isInsert);\n\n // Next, merge those two ends\n var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);\n if (first) {\n // Fix up .to properties of first\n for (var i = 0; i < first.length; ++i) {\n var span = first[i];\n if (span.to == null) {\n var found = getMarkedSpanFor(last, span.marker);\n if (!found) { span.to = startCh; }\n else if (sameLine) { span.to = found.to == null ? null : found.to + offset; }\n }\n }\n }\n if (last) {\n // Fix up .from in last (or move them into first in case of sameLine)\n for (var i$1 = 0; i$1 < last.length; ++i$1) {\n var span$1 = last[i$1];\n if (span$1.to != null) { span$1.to += offset; }\n if (span$1.from == null) {\n var found$1 = getMarkedSpanFor(first, span$1.marker);\n if (!found$1) {\n span$1.from = offset;\n if (sameLine) { (first || (first = [])).push(span$1); }\n }\n } else {\n span$1.from += offset;\n if (sameLine) { (first || (first = [])).push(span$1); }\n }\n }\n }\n // Make sure we didn't create any zero-length spans\n if (first) { first = clearEmptySpans(first); }\n if (last && last != first) { last = clearEmptySpans(last); }\n\n var newMarkers = [first];\n if (!sameLine) {\n // Fill gap with whole-line-spans\n var gap = change.text.length - 2, gapMarkers;\n if (gap > 0 && first)\n { for (var i$2 = 0; i$2 < first.length; ++i$2)\n { if (first[i$2].to == null)\n { (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$2].marker, null, null)); } } }\n for (var i$3 = 0; i$3 < gap; ++i$3)\n { newMarkers.push(gapMarkers); }\n newMarkers.push(last);\n }\n return newMarkers\n }\n\n // Remove spans that are empty and don't have a clearWhenEmpty\n // option of false.\n function clearEmptySpans(spans) {\n for (var i = 0; i < spans.length; ++i) {\n var span = spans[i];\n if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)\n { spans.splice(i--, 1); }\n }\n if (!spans.length) { return null }\n return spans\n }\n\n // Used to 'clip' out readOnly ranges when making a change.\n function removeReadOnlyRanges(doc, from, to) {\n var markers = null;\n doc.iter(from.line, to.line + 1, function (line) {\n if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {\n var mark = line.markedSpans[i].marker;\n if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))\n { (markers || (markers = [])).push(mark); }\n } }\n });\n if (!markers) { return null }\n var parts = [{from: from, to: to}];\n for (var i = 0; i < markers.length; ++i) {\n var mk = markers[i], m = mk.find(0);\n for (var j = 0; j < parts.length; ++j) {\n var p = parts[j];\n if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) { continue }\n var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to);\n if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)\n { newParts.push({from: p.from, to: m.from}); }\n if (dto > 0 || !mk.inclusiveRight && !dto)\n { newParts.push({from: m.to, to: p.to}); }\n parts.splice.apply(parts, newParts);\n j += newParts.length - 3;\n }\n }\n return parts\n }\n\n // Connect or disconnect spans from a line.\n function detachMarkedSpans(line) {\n var spans = line.markedSpans;\n if (!spans) { return }\n for (var i = 0; i < spans.length; ++i)\n { spans[i].marker.detachLine(line); }\n line.markedSpans = null;\n }\n function attachMarkedSpans(line, spans) {\n if (!spans) { return }\n for (var i = 0; i < spans.length; ++i)\n { spans[i].marker.attachLine(line); }\n line.markedSpans = spans;\n }\n\n // Helpers used when computing which overlapping collapsed span\n // counts as the larger one.\n function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0 }\n function extraRight(marker) { return marker.inclusiveRight ? 1 : 0 }\n\n // Returns a number indicating which of two overlapping collapsed\n // spans is larger (and thus includes the other). Falls back to\n // comparing ids when the spans cover exactly the same range.\n function compareCollapsedMarkers(a, b) {\n var lenDiff = a.lines.length - b.lines.length;\n if (lenDiff != 0) { return lenDiff }\n var aPos = a.find(), bPos = b.find();\n var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);\n if (fromCmp) { return -fromCmp }\n var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);\n if (toCmp) { return toCmp }\n return b.id - a.id\n }\n\n // Find out whether a line ends or starts in a collapsed span. If\n // so, return the marker for that span.\n function collapsedSpanAtSide(line, start) {\n var sps = sawCollapsedSpans && line.markedSpans, found;\n if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {\n sp = sps[i];\n if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&\n (!found || compareCollapsedMarkers(found, sp.marker) < 0))\n { found = sp.marker; }\n } }\n return found\n }\n function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true) }\n function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false) }\n\n function collapsedSpanAround(line, ch) {\n var sps = sawCollapsedSpans && line.markedSpans, found;\n if (sps) { for (var i = 0; i < sps.length; ++i) {\n var sp = sps[i];\n if (sp.marker.collapsed && (sp.from == null || sp.from < ch) && (sp.to == null || sp.to > ch) &&\n (!found || compareCollapsedMarkers(found, sp.marker) < 0)) { found = sp.marker; }\n } }\n return found\n }\n\n // Test whether there exists a collapsed span that partially\n // overlaps (covers the start or end, but not both) of a new span.\n // Such overlap is not allowed.\n function conflictingCollapsedRange(doc, lineNo, from, to, marker) {\n var line = getLine(doc, lineNo);\n var sps = sawCollapsedSpans && line.markedSpans;\n if (sps) { for (var i = 0; i < sps.length; ++i) {\n var sp = sps[i];\n if (!sp.marker.collapsed) { continue }\n var found = sp.marker.find(0);\n var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);\n var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);\n if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) { continue }\n if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) ||\n fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0))\n { return true }\n } }\n }\n\n // A visual line is a line as drawn on the screen. Folding, for\n // example, can cause multiple logical lines to appear on the same\n // visual line. This finds the start of the visual line that the\n // given line is part of (usually that is the line itself).\n function visualLine(line) {\n var merged;\n while (merged = collapsedSpanAtStart(line))\n { line = merged.find(-1, true).line; }\n return line\n }\n\n function visualLineEnd(line) {\n var merged;\n while (merged = collapsedSpanAtEnd(line))\n { line = merged.find(1, true).line; }\n return line\n }\n\n // Returns an array of logical lines that continue the visual line\n // started by the argument, or undefined if there are no such lines.\n function visualLineContinued(line) {\n var merged, lines;\n while (merged = collapsedSpanAtEnd(line)) {\n line = merged.find(1, true).line\n ;(lines || (lines = [])).push(line);\n }\n return lines\n }\n\n // Get the line number of the start of the visual line that the\n // given line number is part of.\n function visualLineNo(doc, lineN) {\n var line = getLine(doc, lineN), vis = visualLine(line);\n if (line == vis) { return lineN }\n return lineNo(vis)\n }\n\n // Get the line number of the start of the next visual line after\n // the given line.\n function visualLineEndNo(doc, lineN) {\n if (lineN > doc.lastLine()) { return lineN }\n var line = getLine(doc, lineN), merged;\n if (!lineIsHidden(doc, line)) { return lineN }\n while (merged = collapsedSpanAtEnd(line))\n { line = merged.find(1, true).line; }\n return lineNo(line) + 1\n }\n\n // Compute whether a line is hidden. Lines count as hidden when they\n // are part of a visual line that starts with another line, or when\n // they are entirely covered by collapsed, non-widget span.\n function lineIsHidden(doc, line) {\n var sps = sawCollapsedSpans && line.markedSpans;\n if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {\n sp = sps[i];\n if (!sp.marker.collapsed) { continue }\n if (sp.from == null) { return true }\n if (sp.marker.widgetNode) { continue }\n if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))\n { return true }\n } }\n }\n function lineIsHiddenInner(doc, line, span) {\n if (span.to == null) {\n var end = span.marker.find(1, true);\n return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker))\n }\n if (span.marker.inclusiveRight && span.to == line.text.length)\n { return true }\n for (var sp = (void 0), i = 0; i < line.markedSpans.length; ++i) {\n sp = line.markedSpans[i];\n if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&\n (sp.to == null || sp.to != span.from) &&\n (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&\n lineIsHiddenInner(doc, line, sp)) { return true }\n }\n }\n\n // Find the height above the given line.\n function heightAtLine(lineObj) {\n lineObj = visualLine(lineObj);\n\n var h = 0, chunk = lineObj.parent;\n for (var i = 0; i < chunk.lines.length; ++i) {\n var line = chunk.lines[i];\n if (line == lineObj) { break }\n else { h += line.height; }\n }\n for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {\n for (var i$1 = 0; i$1 < p.children.length; ++i$1) {\n var cur = p.children[i$1];\n if (cur == chunk) { break }\n else { h += cur.height; }\n }\n }\n return h\n }\n\n // Compute the character length of a line, taking into account\n // collapsed ranges (see markText) that might hide parts, and join\n // other lines onto it.\n function lineLength(line) {\n if (line.height == 0) { return 0 }\n var len = line.text.length, merged, cur = line;\n while (merged = collapsedSpanAtStart(cur)) {\n var found = merged.find(0, true);\n cur = found.from.line;\n len += found.from.ch - found.to.ch;\n }\n cur = line;\n while (merged = collapsedSpanAtEnd(cur)) {\n var found$1 = merged.find(0, true);\n len -= cur.text.length - found$1.from.ch;\n cur = found$1.to.line;\n len += cur.text.length - found$1.to.ch;\n }\n return len\n }\n\n // Find the longest line in the document.\n function findMaxLine(cm) {\n var d = cm.display, doc = cm.doc;\n d.maxLine = getLine(doc, doc.first);\n d.maxLineLength = lineLength(d.maxLine);\n d.maxLineChanged = true;\n doc.iter(function (line) {\n var len = lineLength(line);\n if (len > d.maxLineLength) {\n d.maxLineLength = len;\n d.maxLine = line;\n }\n });\n }\n\n // LINE DATA STRUCTURE\n\n // Line objects. These hold state related to a line, including\n // highlighting info (the styles array).\n var Line = function(text, markedSpans, estimateHeight) {\n this.text = text;\n attachMarkedSpans(this, markedSpans);\n this.height = estimateHeight ? estimateHeight(this) : 1;\n };\n\n Line.prototype.lineNo = function () { return lineNo(this) };\n eventMixin(Line);\n\n // Change the content (text, markers) of a line. Automatically\n // invalidates cached information and tries to re-estimate the\n // line's height.\n function updateLine(line, text, markedSpans, estimateHeight) {\n line.text = text;\n if (line.stateAfter) { line.stateAfter = null; }\n if (line.styles) { line.styles = null; }\n if (line.order != null) { line.order = null; }\n detachMarkedSpans(line);\n attachMarkedSpans(line, markedSpans);\n var estHeight = estimateHeight ? estimateHeight(line) : 1;\n if (estHeight != line.height) { updateLineHeight(line, estHeight); }\n }\n\n // Detach a line from the document tree and its markers.\n function cleanUpLine(line) {\n line.parent = null;\n detachMarkedSpans(line);\n }\n\n // Convert a style as returned by a mode (either null, or a string\n // containing one or more styles) to a CSS style. This is cached,\n // and also looks for line-wide styles.\n var styleToClassCache = {}, styleToClassCacheWithMode = {};\n function interpretTokenStyle(style, options) {\n if (!style || /^\\s*$/.test(style)) { return null }\n var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;\n return cache[style] ||\n (cache[style] = style.replace(/\\S+/g, \"cm-$&\"))\n }\n\n // Render the DOM representation of the text of a line. Also builds\n // up a 'line map', which points at the DOM nodes that represent\n // specific stretches of text, and is used by the measuring code.\n // The returned object contains the DOM node, this map, and\n // information about line-wide styles that were set by the mode.\n function buildLineContent(cm, lineView) {\n // The padding-right forces the element to have a 'border', which\n // is needed on Webkit to be able to get line-level bounding\n // rectangles for it (in measureChar).\n var content = eltP(\"span\", null, null, webkit ? \"padding-right: .1px\" : null);\n var builder = {pre: eltP(\"pre\", [content], \"CodeMirror-line\"), content: content,\n col: 0, pos: 0, cm: cm,\n trailingSpace: false,\n splitSpaces: cm.getOption(\"lineWrapping\")};\n lineView.measure = {};\n\n // Iterate over the logical lines that make up this visual line.\n for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {\n var line = i ? lineView.rest[i - 1] : lineView.line, order = (void 0);\n builder.pos = 0;\n builder.addToken = buildToken;\n // Optionally wire in some hacks into the token-rendering\n // algorithm, to deal with browser quirks.\n if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line, cm.doc.direction)))\n { builder.addToken = buildTokenBadBidi(builder.addToken, order); }\n builder.map = [];\n var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line);\n insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate));\n if (line.styleClasses) {\n if (line.styleClasses.bgClass)\n { builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || \"\"); }\n if (line.styleClasses.textClass)\n { builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || \"\"); }\n }\n\n // Ensure at least a single node is present, for measuring.\n if (builder.map.length == 0)\n { builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))); }\n\n // Store the map and a cache object for the current logical line\n if (i == 0) {\n lineView.measure.map = builder.map;\n lineView.measure.cache = {};\n } else {\n (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map)\n ;(lineView.measure.caches || (lineView.measure.caches = [])).push({});\n }\n }\n\n // See issue #2901\n if (webkit) {\n var last = builder.content.lastChild;\n if (/\\bcm-tab\\b/.test(last.className) || (last.querySelector && last.querySelector(\".cm-tab\")))\n { builder.content.className = \"cm-tab-wrap-hack\"; }\n }\n\n signal(cm, \"renderLine\", cm, lineView.line, builder.pre);\n if (builder.pre.className)\n { builder.textClass = joinClasses(builder.pre.className, builder.textClass || \"\"); }\n\n return builder\n }\n\n function defaultSpecialCharPlaceholder(ch) {\n var token = elt(\"span\", \"\\u2022\", \"cm-invalidchar\");\n token.title = \"\\\\u\" + ch.charCodeAt(0).toString(16);\n token.setAttribute(\"aria-label\", token.title);\n return token\n }\n\n // Build up the DOM representation for a single token, and add it to\n // the line map. Takes care to render special characters separately.\n function buildToken(builder, text, style, startStyle, endStyle, css, attributes) {\n if (!text) { return }\n var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text;\n var special = builder.cm.state.specialChars, mustWrap = false;\n var content;\n if (!special.test(text)) {\n builder.col += text.length;\n content = document.createTextNode(displayText);\n builder.map.push(builder.pos, builder.pos + text.length, content);\n if (ie && ie_version < 9) { mustWrap = true; }\n builder.pos += text.length;\n } else {\n content = document.createDocumentFragment();\n var pos = 0;\n while (true) {\n special.lastIndex = pos;\n var m = special.exec(text);\n var skipped = m ? m.index - pos : text.length - pos;\n if (skipped) {\n var txt = document.createTextNode(displayText.slice(pos, pos + skipped));\n if (ie && ie_version < 9) { content.appendChild(elt(\"span\", [txt])); }\n else { content.appendChild(txt); }\n builder.map.push(builder.pos, builder.pos + skipped, txt);\n builder.col += skipped;\n builder.pos += skipped;\n }\n if (!m) { break }\n pos += skipped + 1;\n var txt$1 = (void 0);\n if (m[0] == \"\\t\") {\n var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;\n txt$1 = content.appendChild(elt(\"span\", spaceStr(tabWidth), \"cm-tab\"));\n txt$1.setAttribute(\"role\", \"presentation\");\n txt$1.setAttribute(\"cm-text\", \"\\t\");\n builder.col += tabWidth;\n } else if (m[0] == \"\\r\" || m[0] == \"\\n\") {\n txt$1 = content.appendChild(elt(\"span\", m[0] == \"\\r\" ? \"\\u240d\" : \"\\u2424\", \"cm-invalidchar\"));\n txt$1.setAttribute(\"cm-text\", m[0]);\n builder.col += 1;\n } else {\n txt$1 = builder.cm.options.specialCharPlaceholder(m[0]);\n txt$1.setAttribute(\"cm-text\", m[0]);\n if (ie && ie_version < 9) { content.appendChild(elt(\"span\", [txt$1])); }\n else { content.appendChild(txt$1); }\n builder.col += 1;\n }\n builder.map.push(builder.pos, builder.pos + 1, txt$1);\n builder.pos++;\n }\n }\n builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32;\n if (style || startStyle || endStyle || mustWrap || css || attributes) {\n var fullStyle = style || \"\";\n if (startStyle) { fullStyle += startStyle; }\n if (endStyle) { fullStyle += endStyle; }\n var token = elt(\"span\", [content], fullStyle, css);\n if (attributes) {\n for (var attr in attributes) { if (attributes.hasOwnProperty(attr) && attr != \"style\" && attr != \"class\")\n { token.setAttribute(attr, attributes[attr]); } }\n }\n return builder.content.appendChild(token)\n }\n builder.content.appendChild(content);\n }\n\n // Change some spaces to NBSP to prevent the browser from collapsing\n // trailing spaces at the end of a line when rendering text (issue #1362).\n function splitSpaces(text, trailingBefore) {\n if (text.length > 1 && !/ /.test(text)) { return text }\n var spaceBefore = trailingBefore, result = \"\";\n for (var i = 0; i < text.length; i++) {\n var ch = text.charAt(i);\n if (ch == \" \" && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32))\n { ch = \"\\u00a0\"; }\n result += ch;\n spaceBefore = ch == \" \";\n }\n return result\n }\n\n // Work around nonsense dimensions being reported for stretches of\n // right-to-left text.\n function buildTokenBadBidi(inner, order) {\n return function (builder, text, style, startStyle, endStyle, css, attributes) {\n style = style ? style + \" cm-force-border\" : \"cm-force-border\";\n var start = builder.pos, end = start + text.length;\n for (;;) {\n // Find the part that overlaps with the start of this text\n var part = (void 0);\n for (var i = 0; i < order.length; i++) {\n part = order[i];\n if (part.to > start && part.from <= start) { break }\n }\n if (part.to >= end) { return inner(builder, text, style, startStyle, endStyle, css, attributes) }\n inner(builder, text.slice(0, part.to - start), style, startStyle, null, css, attributes);\n startStyle = null;\n text = text.slice(part.to - start);\n start = part.to;\n }\n }\n }\n\n function buildCollapsedSpan(builder, size, marker, ignoreWidget) {\n var widget = !ignoreWidget && marker.widgetNode;\n if (widget) { builder.map.push(builder.pos, builder.pos + size, widget); }\n if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {\n if (!widget)\n { widget = builder.content.appendChild(document.createElement(\"span\")); }\n widget.setAttribute(\"cm-marker\", marker.id);\n }\n if (widget) {\n builder.cm.display.input.setUneditable(widget);\n builder.content.appendChild(widget);\n }\n builder.pos += size;\n builder.trailingSpace = false;\n }\n\n // Outputs a number of spans to make up a line, taking highlighting\n // and marked text into account.\n function insertLineContent(line, builder, styles) {\n var spans = line.markedSpans, allText = line.text, at = 0;\n if (!spans) {\n for (var i$1 = 1; i$1 < styles.length; i$1+=2)\n { builder.addToken(builder, allText.slice(at, at = styles[i$1]), interpretTokenStyle(styles[i$1+1], builder.cm.options)); }\n return\n }\n\n var len = allText.length, pos = 0, i = 1, text = \"\", style, css;\n var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, collapsed, attributes;\n for (;;) {\n if (nextChange == pos) { // Update current marker set\n spanStyle = spanEndStyle = spanStartStyle = css = \"\";\n attributes = null;\n collapsed = null; nextChange = Infinity;\n var foundBookmarks = [], endStyles = (void 0);\n for (var j = 0; j < spans.length; ++j) {\n var sp = spans[j], m = sp.marker;\n if (m.type == \"bookmark\" && sp.from == pos && m.widgetNode) {\n foundBookmarks.push(m);\n } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {\n if (sp.to != null && sp.to != pos && nextChange > sp.to) {\n nextChange = sp.to;\n spanEndStyle = \"\";\n }\n if (m.className) { spanStyle += \" \" + m.className; }\n if (m.css) { css = (css ? css + \";\" : \"\") + m.css; }\n if (m.startStyle && sp.from == pos) { spanStartStyle += \" \" + m.startStyle; }\n if (m.endStyle && sp.to == nextChange) { (endStyles || (endStyles = [])).push(m.endStyle, sp.to); }\n // support for the old title property\n // https://github.com/codemirror/CodeMirror/pull/5673\n if (m.title) { (attributes || (attributes = {})).title = m.title; }\n if (m.attributes) {\n for (var attr in m.attributes)\n { (attributes || (attributes = {}))[attr] = m.attributes[attr]; }\n }\n if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))\n { collapsed = sp; }\n } else if (sp.from > pos && nextChange > sp.from) {\n nextChange = sp.from;\n }\n }\n if (endStyles) { for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2)\n { if (endStyles[j$1 + 1] == nextChange) { spanEndStyle += \" \" + endStyles[j$1]; } } }\n\n if (!collapsed || collapsed.from == pos) { for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2)\n { buildCollapsedSpan(builder, 0, foundBookmarks[j$2]); } }\n if (collapsed && (collapsed.from || 0) == pos) {\n buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,\n collapsed.marker, collapsed.from == null);\n if (collapsed.to == null) { return }\n if (collapsed.to == pos) { collapsed = false; }\n }\n }\n if (pos >= len) { break }\n\n var upto = Math.min(len, nextChange);\n while (true) {\n if (text) {\n var end = pos + text.length;\n if (!collapsed) {\n var tokenText = end > upto ? text.slice(0, upto - pos) : text;\n builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,\n spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : \"\", css, attributes);\n }\n if (end >= upto) {text = text.slice(upto - pos); pos = upto; break}\n pos = end;\n spanStartStyle = \"\";\n }\n text = allText.slice(at, at = styles[i++]);\n style = interpretTokenStyle(styles[i++], builder.cm.options);\n }\n }\n }\n\n\n // These objects are used to represent the visible (currently drawn)\n // part of the document. A LineView may correspond to multiple\n // logical lines, if those are connected by collapsed ranges.\n function LineView(doc, line, lineN) {\n // The starting line\n this.line = line;\n // Continuing lines, if any\n this.rest = visualLineContinued(line);\n // Number of logical lines in this visual line\n this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;\n this.node = this.text = null;\n this.hidden = lineIsHidden(doc, line);\n }\n\n // Create a range of LineView objects for the given lines.\n function buildViewArray(cm, from, to) {\n var array = [], nextPos;\n for (var pos = from; pos < to; pos = nextPos) {\n var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);\n nextPos = pos + view.size;\n array.push(view);\n }\n return array\n }\n\n var operationGroup = null;\n\n function pushOperation(op) {\n if (operationGroup) {\n operationGroup.ops.push(op);\n } else {\n op.ownsGroup = operationGroup = {\n ops: [op],\n delayedCallbacks: []\n };\n }\n }\n\n function fireCallbacksForOps(group) {\n // Calls delayed callbacks and cursorActivity handlers until no\n // new ones appear\n var callbacks = group.delayedCallbacks, i = 0;\n do {\n for (; i < callbacks.length; i++)\n { callbacks[i].call(null); }\n for (var j = 0; j < group.ops.length; j++) {\n var op = group.ops[j];\n if (op.cursorActivityHandlers)\n { while (op.cursorActivityCalled < op.cursorActivityHandlers.length)\n { op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm); } }\n }\n } while (i < callbacks.length)\n }\n\n function finishOperation(op, endCb) {\n var group = op.ownsGroup;\n if (!group) { return }\n\n try { fireCallbacksForOps(group); }\n finally {\n operationGroup = null;\n endCb(group);\n }\n }\n\n var orphanDelayedCallbacks = null;\n\n // Often, we want to signal events at a point where we are in the\n // middle of some work, but don't want the handler to start calling\n // other methods on the editor, which might be in an inconsistent\n // state or simply not expect any other events to happen.\n // signalLater looks whether there are any handlers, and schedules\n // them to be executed when the last operation ends, or, if no\n // operation is active, when a timeout fires.\n function signalLater(emitter, type /*, values...*/) {\n var arr = getHandlers(emitter, type);\n if (!arr.length) { return }\n var args = Array.prototype.slice.call(arguments, 2), list;\n if (operationGroup) {\n list = operationGroup.delayedCallbacks;\n } else if (orphanDelayedCallbacks) {\n list = orphanDelayedCallbacks;\n } else {\n list = orphanDelayedCallbacks = [];\n setTimeout(fireOrphanDelayed, 0);\n }\n var loop = function ( i ) {\n list.push(function () { return arr[i].apply(null, args); });\n };\n\n for (var i = 0; i < arr.length; ++i)\n loop( i );\n }\n\n function fireOrphanDelayed() {\n var delayed = orphanDelayedCallbacks;\n orphanDelayedCallbacks = null;\n for (var i = 0; i < delayed.length; ++i) { delayed[i](); }\n }\n\n // When an aspect of a line changes, a string is added to\n // lineView.changes. This updates the relevant part of the line's\n // DOM structure.\n function updateLineForChanges(cm, lineView, lineN, dims) {\n for (var j = 0; j < lineView.changes.length; j++) {\n var type = lineView.changes[j];\n if (type == \"text\") { updateLineText(cm, lineView); }\n else if (type == \"gutter\") { updateLineGutter(cm, lineView, lineN, dims); }\n else if (type == \"class\") { updateLineClasses(cm, lineView); }\n else if (type == \"widget\") { updateLineWidgets(cm, lineView, dims); }\n }\n lineView.changes = null;\n }\n\n // Lines with gutter elements, widgets or a background class need to\n // be wrapped, and have the extra elements added to the wrapper div\n function ensureLineWrapped(lineView) {\n if (lineView.node == lineView.text) {\n lineView.node = elt(\"div\", null, null, \"position: relative\");\n if (lineView.text.parentNode)\n { lineView.text.parentNode.replaceChild(lineView.node, lineView.text); }\n lineView.node.appendChild(lineView.text);\n if (ie && ie_version < 8) { lineView.node.style.zIndex = 2; }\n }\n return lineView.node\n }\n\n function updateLineBackground(cm, lineView) {\n var cls = lineView.bgClass ? lineView.bgClass + \" \" + (lineView.line.bgClass || \"\") : lineView.line.bgClass;\n if (cls) { cls += \" CodeMirror-linebackground\"; }\n if (lineView.background) {\n if (cls) { lineView.background.className = cls; }\n else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; }\n } else if (cls) {\n var wrap = ensureLineWrapped(lineView);\n lineView.background = wrap.insertBefore(elt(\"div\", null, cls), wrap.firstChild);\n cm.display.input.setUneditable(lineView.background);\n }\n }\n\n // Wrapper around buildLineContent which will reuse the structure\n // in display.externalMeasured when possible.\n function getLineContent(cm, lineView) {\n var ext = cm.display.externalMeasured;\n if (ext && ext.line == lineView.line) {\n cm.display.externalMeasured = null;\n lineView.measure = ext.measure;\n return ext.built\n }\n return buildLineContent(cm, lineView)\n }\n\n // Redraw the line's text. Interacts with the background and text\n // classes because the mode may output tokens that influence these\n // classes.\n function updateLineText(cm, lineView) {\n var cls = lineView.text.className;\n var built = getLineContent(cm, lineView);\n if (lineView.text == lineView.node) { lineView.node = built.pre; }\n lineView.text.parentNode.replaceChild(built.pre, lineView.text);\n lineView.text = built.pre;\n if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {\n lineView.bgClass = built.bgClass;\n lineView.textClass = built.textClass;\n updateLineClasses(cm, lineView);\n } else if (cls) {\n lineView.text.className = cls;\n }\n }\n\n function updateLineClasses(cm, lineView) {\n updateLineBackground(cm, lineView);\n if (lineView.line.wrapClass)\n { ensureLineWrapped(lineView).className = lineView.line.wrapClass; }\n else if (lineView.node != lineView.text)\n { lineView.node.className = \"\"; }\n var textClass = lineView.textClass ? lineView.textClass + \" \" + (lineView.line.textClass || \"\") : lineView.line.textClass;\n lineView.text.className = textClass || \"\";\n }\n\n function updateLineGutter(cm, lineView, lineN, dims) {\n if (lineView.gutter) {\n lineView.node.removeChild(lineView.gutter);\n lineView.gutter = null;\n }\n if (lineView.gutterBackground) {\n lineView.node.removeChild(lineView.gutterBackground);\n lineView.gutterBackground = null;\n }\n if (lineView.line.gutterClass) {\n var wrap = ensureLineWrapped(lineView);\n lineView.gutterBackground = elt(\"div\", null, \"CodeMirror-gutter-background \" + lineView.line.gutterClass,\n (\"left: \" + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + \"px; width: \" + (dims.gutterTotalWidth) + \"px\"));\n cm.display.input.setUneditable(lineView.gutterBackground);\n wrap.insertBefore(lineView.gutterBackground, lineView.text);\n }\n var markers = lineView.line.gutterMarkers;\n if (cm.options.lineNumbers || markers) {\n var wrap$1 = ensureLineWrapped(lineView);\n var gutterWrap = lineView.gutter = elt(\"div\", null, \"CodeMirror-gutter-wrapper\", (\"left: \" + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + \"px\"));\n gutterWrap.setAttribute(\"aria-hidden\", \"true\");\n cm.display.input.setUneditable(gutterWrap);\n wrap$1.insertBefore(gutterWrap, lineView.text);\n if (lineView.line.gutterClass)\n { gutterWrap.className += \" \" + lineView.line.gutterClass; }\n if (cm.options.lineNumbers && (!markers || !markers[\"CodeMirror-linenumbers\"]))\n { lineView.lineNumber = gutterWrap.appendChild(\n elt(\"div\", lineNumberFor(cm.options, lineN),\n \"CodeMirror-linenumber CodeMirror-gutter-elt\",\n (\"left: \" + (dims.gutterLeft[\"CodeMirror-linenumbers\"]) + \"px; width: \" + (cm.display.lineNumInnerWidth) + \"px\"))); }\n if (markers) { for (var k = 0; k < cm.display.gutterSpecs.length; ++k) {\n var id = cm.display.gutterSpecs[k].className, found = markers.hasOwnProperty(id) && markers[id];\n if (found)\n { gutterWrap.appendChild(elt(\"div\", [found], \"CodeMirror-gutter-elt\",\n (\"left: \" + (dims.gutterLeft[id]) + \"px; width: \" + (dims.gutterWidth[id]) + \"px\"))); }\n } }\n }\n }\n\n function updateLineWidgets(cm, lineView, dims) {\n if (lineView.alignable) { lineView.alignable = null; }\n var isWidget = classTest(\"CodeMirror-linewidget\");\n for (var node = lineView.node.firstChild, next = (void 0); node; node = next) {\n next = node.nextSibling;\n if (isWidget.test(node.className)) { lineView.node.removeChild(node); }\n }\n insertLineWidgets(cm, lineView, dims);\n }\n\n // Build a line's DOM representation from scratch\n function buildLineElement(cm, lineView, lineN, dims) {\n var built = getLineContent(cm, lineView);\n lineView.text = lineView.node = built.pre;\n if (built.bgClass) { lineView.bgClass = built.bgClass; }\n if (built.textClass) { lineView.textClass = built.textClass; }\n\n updateLineClasses(cm, lineView);\n updateLineGutter(cm, lineView, lineN, dims);\n insertLineWidgets(cm, lineView, dims);\n return lineView.node\n }\n\n // A lineView may contain multiple logical lines (when merged by\n // collapsed spans). The widgets for all of them need to be drawn.\n function insertLineWidgets(cm, lineView, dims) {\n insertLineWidgetsFor(cm, lineView.line, lineView, dims, true);\n if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)\n { insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false); } }\n }\n\n function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {\n if (!line.widgets) { return }\n var wrap = ensureLineWrapped(lineView);\n for (var i = 0, ws = line.widgets; i < ws.length; ++i) {\n var widget = ws[i], node = elt(\"div\", [widget.node], \"CodeMirror-linewidget\" + (widget.className ? \" \" + widget.className : \"\"));\n if (!widget.handleMouseEvents) { node.setAttribute(\"cm-ignore-events\", \"true\"); }\n positionLineWidget(widget, node, lineView, dims);\n cm.display.input.setUneditable(node);\n if (allowAbove && widget.above)\n { wrap.insertBefore(node, lineView.gutter || lineView.text); }\n else\n { wrap.appendChild(node); }\n signalLater(widget, \"redraw\");\n }\n }\n\n function positionLineWidget(widget, node, lineView, dims) {\n if (widget.noHScroll) {\n (lineView.alignable || (lineView.alignable = [])).push(node);\n var width = dims.wrapperWidth;\n node.style.left = dims.fixedPos + \"px\";\n if (!widget.coverGutter) {\n width -= dims.gutterTotalWidth;\n node.style.paddingLeft = dims.gutterTotalWidth + \"px\";\n }\n node.style.width = width + \"px\";\n }\n if (widget.coverGutter) {\n node.style.zIndex = 5;\n node.style.position = \"relative\";\n if (!widget.noHScroll) { node.style.marginLeft = -dims.gutterTotalWidth + \"px\"; }\n }\n }\n\n function widgetHeight(widget) {\n if (widget.height != null) { return widget.height }\n var cm = widget.doc.cm;\n if (!cm) { return 0 }\n if (!contains(document.body, widget.node)) {\n var parentStyle = \"position: relative;\";\n if (widget.coverGutter)\n { parentStyle += \"margin-left: -\" + cm.display.gutters.offsetWidth + \"px;\"; }\n if (widget.noHScroll)\n { parentStyle += \"width: \" + cm.display.wrapper.clientWidth + \"px;\"; }\n removeChildrenAndAdd(cm.display.measure, elt(\"div\", [widget.node], null, parentStyle));\n }\n return widget.height = widget.node.parentNode.offsetHeight\n }\n\n // Return true when the given mouse event happened in a widget\n function eventInWidget(display, e) {\n for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {\n if (!n || (n.nodeType == 1 && n.getAttribute(\"cm-ignore-events\") == \"true\") ||\n (n.parentNode == display.sizer && n != display.mover))\n { return true }\n }\n }\n\n // POSITION MEASUREMENT\n\n function paddingTop(display) {return display.lineSpace.offsetTop}\n function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight}\n function paddingH(display) {\n if (display.cachedPaddingH) { return display.cachedPaddingH }\n var e = removeChildrenAndAdd(display.measure, elt(\"pre\", \"x\", \"CodeMirror-line-like\"));\n var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;\n var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)};\n if (!isNaN(data.left) && !isNaN(data.right)) { display.cachedPaddingH = data; }\n return data\n }\n\n function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth }\n function displayWidth(cm) {\n return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth\n }\n function displayHeight(cm) {\n return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight\n }\n\n // Ensure the lineView.wrapping.heights array is populated. This is\n // an array of bottom offsets for the lines that make up a drawn\n // line. When lineWrapping is on, there might be more than one\n // height.\n function ensureLineHeights(cm, lineView, rect) {\n var wrapping = cm.options.lineWrapping;\n var curWidth = wrapping && displayWidth(cm);\n if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {\n var heights = lineView.measure.heights = [];\n if (wrapping) {\n lineView.measure.width = curWidth;\n var rects = lineView.text.firstChild.getClientRects();\n for (var i = 0; i < rects.length - 1; i++) {\n var cur = rects[i], next = rects[i + 1];\n if (Math.abs(cur.bottom - next.bottom) > 2)\n { heights.push((cur.bottom + next.top) / 2 - rect.top); }\n }\n }\n heights.push(rect.bottom - rect.top);\n }\n }\n\n // Find a line map (mapping character offsets to text nodes) and a\n // measurement cache for the given line number. (A line view might\n // contain multiple lines when collapsed ranges are present.)\n function mapFromLineView(lineView, line, lineN) {\n if (lineView.line == line)\n { return {map: lineView.measure.map, cache: lineView.measure.cache} }\n if (lineView.rest) {\n for (var i = 0; i < lineView.rest.length; i++)\n { if (lineView.rest[i] == line)\n { return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]} } }\n for (var i$1 = 0; i$1 < lineView.rest.length; i$1++)\n { if (lineNo(lineView.rest[i$1]) > lineN)\n { return {map: lineView.measure.maps[i$1], cache: lineView.measure.caches[i$1], before: true} } }\n }\n }\n\n // Render a line into the hidden node display.externalMeasured. Used\n // when measurement is needed for a line that's not in the viewport.\n function updateExternalMeasurement(cm, line) {\n line = visualLine(line);\n var lineN = lineNo(line);\n var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);\n view.lineN = lineN;\n var built = view.built = buildLineContent(cm, view);\n view.text = built.pre;\n removeChildrenAndAdd(cm.display.lineMeasure, built.pre);\n return view\n }\n\n // Get a {top, bottom, left, right} box (in line-local coordinates)\n // for a given character.\n function measureChar(cm, line, ch, bias) {\n return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias)\n }\n\n // Find a line view that corresponds to the given line number.\n function findViewForLine(cm, lineN) {\n if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)\n { return cm.display.view[findViewIndex(cm, lineN)] }\n var ext = cm.display.externalMeasured;\n if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)\n { return ext }\n }\n\n // Measurement can be split in two steps, the set-up work that\n // applies to the whole line, and the measurement of the actual\n // character. Functions like coordsChar, that need to do a lot of\n // measurements in a row, can thus ensure that the set-up work is\n // only done once.\n function prepareMeasureForLine(cm, line) {\n var lineN = lineNo(line);\n var view = findViewForLine(cm, lineN);\n if (view && !view.text) {\n view = null;\n } else if (view && view.changes) {\n updateLineForChanges(cm, view, lineN, getDimensions(cm));\n cm.curOp.forceUpdate = true;\n }\n if (!view)\n { view = updateExternalMeasurement(cm, line); }\n\n var info = mapFromLineView(view, line, lineN);\n return {\n line: line, view: view, rect: null,\n map: info.map, cache: info.cache, before: info.before,\n hasHeights: false\n }\n }\n\n // Given a prepared measurement object, measures the position of an\n // actual character (or fetches it from the cache).\n function measureCharPrepared(cm, prepared, ch, bias, varHeight) {\n if (prepared.before) { ch = -1; }\n var key = ch + (bias || \"\"), found;\n if (prepared.cache.hasOwnProperty(key)) {\n found = prepared.cache[key];\n } else {\n if (!prepared.rect)\n { prepared.rect = prepared.view.text.getBoundingClientRect(); }\n if (!prepared.hasHeights) {\n ensureLineHeights(cm, prepared.view, prepared.rect);\n prepared.hasHeights = true;\n }\n found = measureCharInner(cm, prepared, ch, bias);\n if (!found.bogus) { prepared.cache[key] = found; }\n }\n return {left: found.left, right: found.right,\n top: varHeight ? found.rtop : found.top,\n bottom: varHeight ? found.rbottom : found.bottom}\n }\n\n var nullRect = {left: 0, right: 0, top: 0, bottom: 0};\n\n function nodeAndOffsetInLineMap(map, ch, bias) {\n var node, start, end, collapse, mStart, mEnd;\n // First, search the line map for the text node corresponding to,\n // or closest to, the target character.\n for (var i = 0; i < map.length; i += 3) {\n mStart = map[i];\n mEnd = map[i + 1];\n if (ch < mStart) {\n start = 0; end = 1;\n collapse = \"left\";\n } else if (ch < mEnd) {\n start = ch - mStart;\n end = start + 1;\n } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) {\n end = mEnd - mStart;\n start = end - 1;\n if (ch >= mEnd) { collapse = \"right\"; }\n }\n if (start != null) {\n node = map[i + 2];\n if (mStart == mEnd && bias == (node.insertLeft ? \"left\" : \"right\"))\n { collapse = bias; }\n if (bias == \"left\" && start == 0)\n { while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) {\n node = map[(i -= 3) + 2];\n collapse = \"left\";\n } }\n if (bias == \"right\" && start == mEnd - mStart)\n { while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) {\n node = map[(i += 3) + 2];\n collapse = \"right\";\n } }\n break\n }\n }\n return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd}\n }\n\n function getUsefulRect(rects, bias) {\n var rect = nullRect;\n if (bias == \"left\") { for (var i = 0; i < rects.length; i++) {\n if ((rect = rects[i]).left != rect.right) { break }\n } } else { for (var i$1 = rects.length - 1; i$1 >= 0; i$1--) {\n if ((rect = rects[i$1]).left != rect.right) { break }\n } }\n return rect\n }\n\n function measureCharInner(cm, prepared, ch, bias) {\n var place = nodeAndOffsetInLineMap(prepared.map, ch, bias);\n var node = place.node, start = place.start, end = place.end, collapse = place.collapse;\n\n var rect;\n if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.\n for (var i$1 = 0; i$1 < 4; i$1++) { // Retry a maximum of 4 times when nonsense rectangles are returned\n while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) { --start; }\n while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) { ++end; }\n if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart)\n { rect = node.parentNode.getBoundingClientRect(); }\n else\n { rect = getUsefulRect(range(node, start, end).getClientRects(), bias); }\n if (rect.left || rect.right || start == 0) { break }\n end = start;\n start = start - 1;\n collapse = \"right\";\n }\n if (ie && ie_version < 11) { rect = maybeUpdateRectForZooming(cm.display.measure, rect); }\n } else { // If it is a widget, simply get the box for the whole widget.\n if (start > 0) { collapse = bias = \"right\"; }\n var rects;\n if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)\n { rect = rects[bias == \"right\" ? rects.length - 1 : 0]; }\n else\n { rect = node.getBoundingClientRect(); }\n }\n if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {\n var rSpan = node.parentNode.getClientRects()[0];\n if (rSpan)\n { rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom}; }\n else\n { rect = nullRect; }\n }\n\n var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top;\n var mid = (rtop + rbot) / 2;\n var heights = prepared.view.measure.heights;\n var i = 0;\n for (; i < heights.length - 1; i++)\n { if (mid < heights[i]) { break } }\n var top = i ? heights[i - 1] : 0, bot = heights[i];\n var result = {left: (collapse == \"right\" ? rect.right : rect.left) - prepared.rect.left,\n right: (collapse == \"left\" ? rect.left : rect.right) - prepared.rect.left,\n top: top, bottom: bot};\n if (!rect.left && !rect.right) { result.bogus = true; }\n if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; }\n\n return result\n }\n\n // Work around problem with bounding client rects on ranges being\n // returned incorrectly when zoomed on IE10 and below.\n function maybeUpdateRectForZooming(measure, rect) {\n if (!window.screen || screen.logicalXDPI == null ||\n screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))\n { return rect }\n var scaleX = screen.logicalXDPI / screen.deviceXDPI;\n var scaleY = screen.logicalYDPI / screen.deviceYDPI;\n return {left: rect.left * scaleX, right: rect.right * scaleX,\n top: rect.top * scaleY, bottom: rect.bottom * scaleY}\n }\n\n function clearLineMeasurementCacheFor(lineView) {\n if (lineView.measure) {\n lineView.measure.cache = {};\n lineView.measure.heights = null;\n if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)\n { lineView.measure.caches[i] = {}; } }\n }\n }\n\n function clearLineMeasurementCache(cm) {\n cm.display.externalMeasure = null;\n removeChildren(cm.display.lineMeasure);\n for (var i = 0; i < cm.display.view.length; i++)\n { clearLineMeasurementCacheFor(cm.display.view[i]); }\n }\n\n function clearCaches(cm) {\n clearLineMeasurementCache(cm);\n cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;\n if (!cm.options.lineWrapping) { cm.display.maxLineChanged = true; }\n cm.display.lineNumChars = null;\n }\n\n function pageScrollX(doc) {\n // Work around https://bugs.chromium.org/p/chromium/issues/detail?id=489206\n // which causes page_Offset and bounding client rects to use\n // different reference viewports and invalidate our calculations.\n if (chrome && android) { return -(doc.body.getBoundingClientRect().left - parseInt(getComputedStyle(doc.body).marginLeft)) }\n return doc.defaultView.pageXOffset || (doc.documentElement || doc.body).scrollLeft\n }\n function pageScrollY(doc) {\n if (chrome && android) { return -(doc.body.getBoundingClientRect().top - parseInt(getComputedStyle(doc.body).marginTop)) }\n return doc.defaultView.pageYOffset || (doc.documentElement || doc.body).scrollTop\n }\n\n function widgetTopHeight(lineObj) {\n var ref = visualLine(lineObj);\n var widgets = ref.widgets;\n var height = 0;\n if (widgets) { for (var i = 0; i < widgets.length; ++i) { if (widgets[i].above)\n { height += widgetHeight(widgets[i]); } } }\n return height\n }\n\n // Converts a {top, bottom, left, right} box from line-local\n // coordinates into another coordinate system. Context may be one of\n // \"line\", \"div\" (display.lineDiv), \"local\"./null (editor), \"window\",\n // or \"page\".\n function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) {\n if (!includeWidgets) {\n var height = widgetTopHeight(lineObj);\n rect.top += height; rect.bottom += height;\n }\n if (context == \"line\") { return rect }\n if (!context) { context = \"local\"; }\n var yOff = heightAtLine(lineObj);\n if (context == \"local\") { yOff += paddingTop(cm.display); }\n else { yOff -= cm.display.viewOffset; }\n if (context == \"page\" || context == \"window\") {\n var lOff = cm.display.lineSpace.getBoundingClientRect();\n yOff += lOff.top + (context == \"window\" ? 0 : pageScrollY(doc(cm)));\n var xOff = lOff.left + (context == \"window\" ? 0 : pageScrollX(doc(cm)));\n rect.left += xOff; rect.right += xOff;\n }\n rect.top += yOff; rect.bottom += yOff;\n return rect\n }\n\n // Coverts a box from \"div\" coords to another coordinate system.\n // Context may be \"window\", \"page\", \"div\", or \"local\"./null.\n function fromCoordSystem(cm, coords, context) {\n if (context == \"div\") { return coords }\n var left = coords.left, top = coords.top;\n // First move into \"page\" coordinate system\n if (context == \"page\") {\n left -= pageScrollX(doc(cm));\n top -= pageScrollY(doc(cm));\n } else if (context == \"local\" || !context) {\n var localBox = cm.display.sizer.getBoundingClientRect();\n left += localBox.left;\n top += localBox.top;\n }\n\n var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();\n return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top}\n }\n\n function charCoords(cm, pos, context, lineObj, bias) {\n if (!lineObj) { lineObj = getLine(cm.doc, pos.line); }\n return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context)\n }\n\n // Returns a box for a given cursor position, which may have an\n // 'other' property containing the position of the secondary cursor\n // on a bidi boundary.\n // A cursor Pos(line, char, \"before\") is on the same visual line as `char - 1`\n // and after `char - 1` in writing order of `char - 1`\n // A cursor Pos(line, char, \"after\") is on the same visual line as `char`\n // and before `char` in writing order of `char`\n // Examples (upper-case letters are RTL, lower-case are LTR):\n // Pos(0, 1, ...)\n // before after\n // ab a|b a|b\n // aB a|B aB|\n // Ab |Ab A|b\n // AB B|A B|A\n // Every position after the last character on a line is considered to stick\n // to the last character on the line.\n function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {\n lineObj = lineObj || getLine(cm.doc, pos.line);\n if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }\n function get(ch, right) {\n var m = measureCharPrepared(cm, preparedMeasure, ch, right ? \"right\" : \"left\", varHeight);\n if (right) { m.left = m.right; } else { m.right = m.left; }\n return intoCoordSystem(cm, lineObj, m, context)\n }\n var order = getOrder(lineObj, cm.doc.direction), ch = pos.ch, sticky = pos.sticky;\n if (ch >= lineObj.text.length) {\n ch = lineObj.text.length;\n sticky = \"before\";\n } else if (ch <= 0) {\n ch = 0;\n sticky = \"after\";\n }\n if (!order) { return get(sticky == \"before\" ? ch - 1 : ch, sticky == \"before\") }\n\n function getBidi(ch, partPos, invert) {\n var part = order[partPos], right = part.level == 1;\n return get(invert ? ch - 1 : ch, right != invert)\n }\n var partPos = getBidiPartAt(order, ch, sticky);\n var other = bidiOther;\n var val = getBidi(ch, partPos, sticky == \"before\");\n if (other != null) { val.other = getBidi(ch, other, sticky != \"before\"); }\n return val\n }\n\n // Used to cheaply estimate the coordinates for a position. Used for\n // intermediate scroll updates.\n function estimateCoords(cm, pos) {\n var left = 0;\n pos = clipPos(cm.doc, pos);\n if (!cm.options.lineWrapping) { left = charWidth(cm.display) * pos.ch; }\n var lineObj = getLine(cm.doc, pos.line);\n var top = heightAtLine(lineObj) + paddingTop(cm.display);\n return {left: left, right: left, top: top, bottom: top + lineObj.height}\n }\n\n // Positions returned by coordsChar contain some extra information.\n // xRel is the relative x position of the input coordinates compared\n // to the found position (so xRel > 0 means the coordinates are to\n // the right of the character position, for example). When outside\n // is true, that means the coordinates lie outside the line's\n // vertical range.\n function PosWithInfo(line, ch, sticky, outside, xRel) {\n var pos = Pos(line, ch, sticky);\n pos.xRel = xRel;\n if (outside) { pos.outside = outside; }\n return pos\n }\n\n // Compute the character position closest to the given coordinates.\n // Input must be lineSpace-local (\"div\" coordinate system).\n function coordsChar(cm, x, y) {\n var doc = cm.doc;\n y += cm.display.viewOffset;\n if (y < 0) { return PosWithInfo(doc.first, 0, null, -1, -1) }\n var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;\n if (lineN > last)\n { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, 1, 1) }\n if (x < 0) { x = 0; }\n\n var lineObj = getLine(doc, lineN);\n for (;;) {\n var found = coordsCharInner(cm, lineObj, lineN, x, y);\n var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 || found.outside > 0 ? 1 : 0));\n if (!collapsed) { return found }\n var rangeEnd = collapsed.find(1);\n if (rangeEnd.line == lineN) { return rangeEnd }\n lineObj = getLine(doc, lineN = rangeEnd.line);\n }\n }\n\n function wrappedLineExtent(cm, lineObj, preparedMeasure, y) {\n y -= widgetTopHeight(lineObj);\n var end = lineObj.text.length;\n var begin = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch - 1).bottom <= y; }, end, 0);\n end = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch).top > y; }, begin, end);\n return {begin: begin, end: end}\n }\n\n function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) {\n if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }\n var targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), \"line\").top;\n return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop)\n }\n\n // Returns true if the given side of a box is after the given\n // coordinates, in top-to-bottom, left-to-right order.\n function boxIsAfter(box, x, y, left) {\n return box.bottom <= y ? false : box.top > y ? true : (left ? box.left : box.right) > x\n }\n\n function coordsCharInner(cm, lineObj, lineNo, x, y) {\n // Move y into line-local coordinate space\n y -= heightAtLine(lineObj);\n var preparedMeasure = prepareMeasureForLine(cm, lineObj);\n // When directly calling `measureCharPrepared`, we have to adjust\n // for the widgets at this line.\n var widgetHeight = widgetTopHeight(lineObj);\n var begin = 0, end = lineObj.text.length, ltr = true;\n\n var order = getOrder(lineObj, cm.doc.direction);\n // If the line isn't plain left-to-right text, first figure out\n // which bidi section the coordinates fall into.\n if (order) {\n var part = (cm.options.lineWrapping ? coordsBidiPartWrapped : coordsBidiPart)\n (cm, lineObj, lineNo, preparedMeasure, order, x, y);\n ltr = part.level != 1;\n // The awkward -1 offsets are needed because findFirst (called\n // on these below) will treat its first bound as inclusive,\n // second as exclusive, but we want to actually address the\n // characters in the part's range\n begin = ltr ? part.from : part.to - 1;\n end = ltr ? part.to : part.from - 1;\n }\n\n // A binary search to find the first character whose bounding box\n // starts after the coordinates. If we run across any whose box wrap\n // the coordinates, store that.\n var chAround = null, boxAround = null;\n var ch = findFirst(function (ch) {\n var box = measureCharPrepared(cm, preparedMeasure, ch);\n box.top += widgetHeight; box.bottom += widgetHeight;\n if (!boxIsAfter(box, x, y, false)) { return false }\n if (box.top <= y && box.left <= x) {\n chAround = ch;\n boxAround = box;\n }\n return true\n }, begin, end);\n\n var baseX, sticky, outside = false;\n // If a box around the coordinates was found, use that\n if (boxAround) {\n // Distinguish coordinates nearer to the left or right side of the box\n var atLeft = x - boxAround.left < boxAround.right - x, atStart = atLeft == ltr;\n ch = chAround + (atStart ? 0 : 1);\n sticky = atStart ? \"after\" : \"before\";\n baseX = atLeft ? boxAround.left : boxAround.right;\n } else {\n // (Adjust for extended bound, if necessary.)\n if (!ltr && (ch == end || ch == begin)) { ch++; }\n // To determine which side to associate with, get the box to the\n // left of the character and compare it's vertical position to the\n // coordinates\n sticky = ch == 0 ? \"after\" : ch == lineObj.text.length ? \"before\" :\n (measureCharPrepared(cm, preparedMeasure, ch - (ltr ? 1 : 0)).bottom + widgetHeight <= y) == ltr ?\n \"after\" : \"before\";\n // Now get accurate coordinates for this place, in order to get a\n // base X position\n var coords = cursorCoords(cm, Pos(lineNo, ch, sticky), \"line\", lineObj, preparedMeasure);\n baseX = coords.left;\n outside = y < coords.top ? -1 : y >= coords.bottom ? 1 : 0;\n }\n\n ch = skipExtendingChars(lineObj.text, ch, 1);\n return PosWithInfo(lineNo, ch, sticky, outside, x - baseX)\n }\n\n function coordsBidiPart(cm, lineObj, lineNo, preparedMeasure, order, x, y) {\n // Bidi parts are sorted left-to-right, and in a non-line-wrapping\n // situation, we can take this ordering to correspond to the visual\n // ordering. This finds the first part whose end is after the given\n // coordinates.\n var index = findFirst(function (i) {\n var part = order[i], ltr = part.level != 1;\n return boxIsAfter(cursorCoords(cm, Pos(lineNo, ltr ? part.to : part.from, ltr ? \"before\" : \"after\"),\n \"line\", lineObj, preparedMeasure), x, y, true)\n }, 0, order.length - 1);\n var part = order[index];\n // If this isn't the first part, the part's start is also after\n // the coordinates, and the coordinates aren't on the same line as\n // that start, move one part back.\n if (index > 0) {\n var ltr = part.level != 1;\n var start = cursorCoords(cm, Pos(lineNo, ltr ? part.from : part.to, ltr ? \"after\" : \"before\"),\n \"line\", lineObj, preparedMeasure);\n if (boxIsAfter(start, x, y, true) && start.top > y)\n { part = order[index - 1]; }\n }\n return part\n }\n\n function coordsBidiPartWrapped(cm, lineObj, _lineNo, preparedMeasure, order, x, y) {\n // In a wrapped line, rtl text on wrapping boundaries can do things\n // that don't correspond to the ordering in our `order` array at\n // all, so a binary search doesn't work, and we want to return a\n // part that only spans one line so that the binary search in\n // coordsCharInner is safe. As such, we first find the extent of the\n // wrapped line, and then do a flat search in which we discard any\n // spans that aren't on the line.\n var ref = wrappedLineExtent(cm, lineObj, preparedMeasure, y);\n var begin = ref.begin;\n var end = ref.end;\n if (/\\s/.test(lineObj.text.charAt(end - 1))) { end--; }\n var part = null, closestDist = null;\n for (var i = 0; i < order.length; i++) {\n var p = order[i];\n if (p.from >= end || p.to <= begin) { continue }\n var ltr = p.level != 1;\n var endX = measureCharPrepared(cm, preparedMeasure, ltr ? Math.min(end, p.to) - 1 : Math.max(begin, p.from)).right;\n // Weigh against spans ending before this, so that they are only\n // picked if nothing ends after\n var dist = endX < x ? x - endX + 1e9 : endX - x;\n if (!part || closestDist > dist) {\n part = p;\n closestDist = dist;\n }\n }\n if (!part) { part = order[order.length - 1]; }\n // Clip the part to the wrapped line.\n if (part.from < begin) { part = {from: begin, to: part.to, level: part.level}; }\n if (part.to > end) { part = {from: part.from, to: end, level: part.level}; }\n return part\n }\n\n var measureText;\n // Compute the default text height.\n function textHeight(display) {\n if (display.cachedTextHeight != null) { return display.cachedTextHeight }\n if (measureText == null) {\n measureText = elt(\"pre\", null, \"CodeMirror-line-like\");\n // Measure a bunch of lines, for browsers that compute\n // fractional heights.\n for (var i = 0; i < 49; ++i) {\n measureText.appendChild(document.createTextNode(\"x\"));\n measureText.appendChild(elt(\"br\"));\n }\n measureText.appendChild(document.createTextNode(\"x\"));\n }\n removeChildrenAndAdd(display.measure, measureText);\n var height = measureText.offsetHeight / 50;\n if (height > 3) { display.cachedTextHeight = height; }\n removeChildren(display.measure);\n return height || 1\n }\n\n // Compute the default character width.\n function charWidth(display) {\n if (display.cachedCharWidth != null) { return display.cachedCharWidth }\n var anchor = elt(\"span\", \"xxxxxxxxxx\");\n var pre = elt(\"pre\", [anchor], \"CodeMirror-line-like\");\n removeChildrenAndAdd(display.measure, pre);\n var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;\n if (width > 2) { display.cachedCharWidth = width; }\n return width || 10\n }\n\n // Do a bulk-read of the DOM positions and sizes needed to draw the\n // view, so that we don't interleave reading and writing to the DOM.\n function getDimensions(cm) {\n var d = cm.display, left = {}, width = {};\n var gutterLeft = d.gutters.clientLeft;\n for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {\n var id = cm.display.gutterSpecs[i].className;\n left[id] = n.offsetLeft + n.clientLeft + gutterLeft;\n width[id] = n.clientWidth;\n }\n return {fixedPos: compensateForHScroll(d),\n gutterTotalWidth: d.gutters.offsetWidth,\n gutterLeft: left,\n gutterWidth: width,\n wrapperWidth: d.wrapper.clientWidth}\n }\n\n // Computes display.scroller.scrollLeft + display.gutters.offsetWidth,\n // but using getBoundingClientRect to get a sub-pixel-accurate\n // result.\n function compensateForHScroll(display) {\n return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left\n }\n\n // Returns a function that estimates the height of a line, to use as\n // first approximation until the line becomes visible (and is thus\n // properly measurable).\n function estimateHeight(cm) {\n var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;\n var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);\n return function (line) {\n if (lineIsHidden(cm.doc, line)) { return 0 }\n\n var widgetsHeight = 0;\n if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) {\n if (line.widgets[i].height) { widgetsHeight += line.widgets[i].height; }\n } }\n\n if (wrapping)\n { return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th }\n else\n { return widgetsHeight + th }\n }\n }\n\n function estimateLineHeights(cm) {\n var doc = cm.doc, est = estimateHeight(cm);\n doc.iter(function (line) {\n var estHeight = est(line);\n if (estHeight != line.height) { updateLineHeight(line, estHeight); }\n });\n }\n\n // Given a mouse event, find the corresponding position. If liberal\n // is false, it checks whether a gutter or scrollbar was clicked,\n // and returns null if it was. forRect is used by rectangular\n // selections, and tries to estimate a character position even for\n // coordinates beyond the right of the text.\n function posFromMouse(cm, e, liberal, forRect) {\n var display = cm.display;\n if (!liberal && e_target(e).getAttribute(\"cm-not-content\") == \"true\") { return null }\n\n var x, y, space = display.lineSpace.getBoundingClientRect();\n // Fails unpredictably on IE[67] when mouse is dragged around quickly.\n try { x = e.clientX - space.left; y = e.clientY - space.top; }\n catch (e$1) { return null }\n var coords = coordsChar(cm, x, y), line;\n if (forRect && coords.xRel > 0 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {\n var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length;\n coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff));\n }\n return coords\n }\n\n // Find the view element corresponding to a given line. Return null\n // when the line isn't visible.\n function findViewIndex(cm, n) {\n if (n >= cm.display.viewTo) { return null }\n n -= cm.display.viewFrom;\n if (n < 0) { return null }\n var view = cm.display.view;\n for (var i = 0; i < view.length; i++) {\n n -= view[i].size;\n if (n < 0) { return i }\n }\n }\n\n // Updates the display.view data structure for a given change to the\n // document. From and to are in pre-change coordinates. Lendiff is\n // the amount of lines added or subtracted by the change. This is\n // used for changes that span multiple lines, or change the way\n // lines are divided into visual lines. regLineChange (below)\n // registers single-line changes.\n function regChange(cm, from, to, lendiff) {\n if (from == null) { from = cm.doc.first; }\n if (to == null) { to = cm.doc.first + cm.doc.size; }\n if (!lendiff) { lendiff = 0; }\n\n var display = cm.display;\n if (lendiff && to < display.viewTo &&\n (display.updateLineNumbers == null || display.updateLineNumbers > from))\n { display.updateLineNumbers = from; }\n\n cm.curOp.viewChanged = true;\n\n if (from >= display.viewTo) { // Change after\n if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)\n { resetView(cm); }\n } else if (to <= display.viewFrom) { // Change before\n if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {\n resetView(cm);\n } else {\n display.viewFrom += lendiff;\n display.viewTo += lendiff;\n }\n } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap\n resetView(cm);\n } else if (from <= display.viewFrom) { // Top overlap\n var cut = viewCuttingPoint(cm, to, to + lendiff, 1);\n if (cut) {\n display.view = display.view.slice(cut.index);\n display.viewFrom = cut.lineN;\n display.viewTo += lendiff;\n } else {\n resetView(cm);\n }\n } else if (to >= display.viewTo) { // Bottom overlap\n var cut$1 = viewCuttingPoint(cm, from, from, -1);\n if (cut$1) {\n display.view = display.view.slice(0, cut$1.index);\n display.viewTo = cut$1.lineN;\n } else {\n resetView(cm);\n }\n } else { // Gap in the middle\n var cutTop = viewCuttingPoint(cm, from, from, -1);\n var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);\n if (cutTop && cutBot) {\n display.view = display.view.slice(0, cutTop.index)\n .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))\n .concat(display.view.slice(cutBot.index));\n display.viewTo += lendiff;\n } else {\n resetView(cm);\n }\n }\n\n var ext = display.externalMeasured;\n if (ext) {\n if (to < ext.lineN)\n { ext.lineN += lendiff; }\n else if (from < ext.lineN + ext.size)\n { display.externalMeasured = null; }\n }\n }\n\n // Register a change to a single line. Type must be one of \"text\",\n // \"gutter\", \"class\", \"widget\"\n function regLineChange(cm, line, type) {\n cm.curOp.viewChanged = true;\n var display = cm.display, ext = cm.display.externalMeasured;\n if (ext && line >= ext.lineN && line < ext.lineN + ext.size)\n { display.externalMeasured = null; }\n\n if (line < display.viewFrom || line >= display.viewTo) { return }\n var lineView = display.view[findViewIndex(cm, line)];\n if (lineView.node == null) { return }\n var arr = lineView.changes || (lineView.changes = []);\n if (indexOf(arr, type) == -1) { arr.push(type); }\n }\n\n // Clear the view.\n function resetView(cm) {\n cm.display.viewFrom = cm.display.viewTo = cm.doc.first;\n cm.display.view = [];\n cm.display.viewOffset = 0;\n }\n\n function viewCuttingPoint(cm, oldN, newN, dir) {\n var index = findViewIndex(cm, oldN), diff, view = cm.display.view;\n if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)\n { return {index: index, lineN: newN} }\n var n = cm.display.viewFrom;\n for (var i = 0; i < index; i++)\n { n += view[i].size; }\n if (n != oldN) {\n if (dir > 0) {\n if (index == view.length - 1) { return null }\n diff = (n + view[index].size) - oldN;\n index++;\n } else {\n diff = n - oldN;\n }\n oldN += diff; newN += diff;\n }\n while (visualLineNo(cm.doc, newN) != newN) {\n if (index == (dir < 0 ? 0 : view.length - 1)) { return null }\n newN += dir * view[index - (dir < 0 ? 1 : 0)].size;\n index += dir;\n }\n return {index: index, lineN: newN}\n }\n\n // Force the view to cover a given range, adding empty view element\n // or clipping off existing ones as needed.\n function adjustView(cm, from, to) {\n var display = cm.display, view = display.view;\n if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {\n display.view = buildViewArray(cm, from, to);\n display.viewFrom = from;\n } else {\n if (display.viewFrom > from)\n { display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view); }\n else if (display.viewFrom < from)\n { display.view = display.view.slice(findViewIndex(cm, from)); }\n display.viewFrom = from;\n if (display.viewTo < to)\n { display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)); }\n else if (display.viewTo > to)\n { display.view = display.view.slice(0, findViewIndex(cm, to)); }\n }\n display.viewTo = to;\n }\n\n // Count the number of lines in the view whose DOM representation is\n // out of date (or nonexistent).\n function countDirtyView(cm) {\n var view = cm.display.view, dirty = 0;\n for (var i = 0; i < view.length; i++) {\n var lineView = view[i];\n if (!lineView.hidden && (!lineView.node || lineView.changes)) { ++dirty; }\n }\n return dirty\n }\n\n function updateSelection(cm) {\n cm.display.input.showSelection(cm.display.input.prepareSelection());\n }\n\n function prepareSelection(cm, primary) {\n if ( primary === void 0 ) primary = true;\n\n var doc = cm.doc, result = {};\n var curFragment = result.cursors = document.createDocumentFragment();\n var selFragment = result.selection = document.createDocumentFragment();\n\n var customCursor = cm.options.$customCursor;\n if (customCursor) { primary = true; }\n for (var i = 0; i < doc.sel.ranges.length; i++) {\n if (!primary && i == doc.sel.primIndex) { continue }\n var range = doc.sel.ranges[i];\n if (range.from().line >= cm.display.viewTo || range.to().line < cm.display.viewFrom) { continue }\n var collapsed = range.empty();\n if (customCursor) {\n var head = customCursor(cm, range);\n if (head) { drawSelectionCursor(cm, head, curFragment); }\n } else if (collapsed || cm.options.showCursorWhenSelecting) {\n drawSelectionCursor(cm, range.head, curFragment);\n }\n if (!collapsed)\n { drawSelectionRange(cm, range, selFragment); }\n }\n return result\n }\n\n // Draws a cursor for the given range\n function drawSelectionCursor(cm, head, output) {\n var pos = cursorCoords(cm, head, \"div\", null, null, !cm.options.singleCursorHeightPerLine);\n\n var cursor = output.appendChild(elt(\"div\", \"\\u00a0\", \"CodeMirror-cursor\"));\n cursor.style.left = pos.left + \"px\";\n cursor.style.top = pos.top + \"px\";\n cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + \"px\";\n\n if (/\\bcm-fat-cursor\\b/.test(cm.getWrapperElement().className)) {\n var charPos = charCoords(cm, head, \"div\", null, null);\n var width = charPos.right - charPos.left;\n cursor.style.width = (width > 0 ? width : cm.defaultCharWidth()) + \"px\";\n }\n\n if (pos.other) {\n // Secondary cursor, shown when on a 'jump' in bi-directional text\n var otherCursor = output.appendChild(elt(\"div\", \"\\u00a0\", \"CodeMirror-cursor CodeMirror-secondarycursor\"));\n otherCursor.style.display = \"\";\n otherCursor.style.left = pos.other.left + \"px\";\n otherCursor.style.top = pos.other.top + \"px\";\n otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + \"px\";\n }\n }\n\n function cmpCoords(a, b) { return a.top - b.top || a.left - b.left }\n\n // Draws the given range as a highlighted selection\n function drawSelectionRange(cm, range, output) {\n var display = cm.display, doc = cm.doc;\n var fragment = document.createDocumentFragment();\n var padding = paddingH(cm.display), leftSide = padding.left;\n var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;\n var docLTR = doc.direction == \"ltr\";\n\n function add(left, top, width, bottom) {\n if (top < 0) { top = 0; }\n top = Math.round(top);\n bottom = Math.round(bottom);\n fragment.appendChild(elt(\"div\", null, \"CodeMirror-selected\", (\"position: absolute; left: \" + left + \"px;\\n top: \" + top + \"px; width: \" + (width == null ? rightSide - left : width) + \"px;\\n height: \" + (bottom - top) + \"px\")));\n }\n\n function drawForLine(line, fromArg, toArg) {\n var lineObj = getLine(doc, line);\n var lineLen = lineObj.text.length;\n var start, end;\n function coords(ch, bias) {\n return charCoords(cm, Pos(line, ch), \"div\", lineObj, bias)\n }\n\n function wrapX(pos, dir, side) {\n var extent = wrappedLineExtentChar(cm, lineObj, null, pos);\n var prop = (dir == \"ltr\") == (side == \"after\") ? \"left\" : \"right\";\n var ch = side == \"after\" ? extent.begin : extent.end - (/\\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1);\n return coords(ch, prop)[prop]\n }\n\n var order = getOrder(lineObj, doc.direction);\n iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) {\n var ltr = dir == \"ltr\";\n var fromPos = coords(from, ltr ? \"left\" : \"right\");\n var toPos = coords(to - 1, ltr ? \"right\" : \"left\");\n\n var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen;\n var first = i == 0, last = !order || i == order.length - 1;\n if (toPos.top - fromPos.top <= 3) { // Single line\n var openLeft = (docLTR ? openStart : openEnd) && first;\n var openRight = (docLTR ? openEnd : openStart) && last;\n var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left;\n var right = openRight ? rightSide : (ltr ? toPos : fromPos).right;\n add(left, fromPos.top, right - left, fromPos.bottom);\n } else { // Multiple lines\n var topLeft, topRight, botLeft, botRight;\n if (ltr) {\n topLeft = docLTR && openStart && first ? leftSide : fromPos.left;\n topRight = docLTR ? rightSide : wrapX(from, dir, \"before\");\n botLeft = docLTR ? leftSide : wrapX(to, dir, \"after\");\n botRight = docLTR && openEnd && last ? rightSide : toPos.right;\n } else {\n topLeft = !docLTR ? leftSide : wrapX(from, dir, \"before\");\n topRight = !docLTR && openStart && first ? rightSide : fromPos.right;\n botLeft = !docLTR && openEnd && last ? leftSide : toPos.left;\n botRight = !docLTR ? rightSide : wrapX(to, dir, \"after\");\n }\n add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom);\n if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top); }\n add(botLeft, toPos.top, botRight - botLeft, toPos.bottom);\n }\n\n if (!start || cmpCoords(fromPos, start) < 0) { start = fromPos; }\n if (cmpCoords(toPos, start) < 0) { start = toPos; }\n if (!end || cmpCoords(fromPos, end) < 0) { end = fromPos; }\n if (cmpCoords(toPos, end) < 0) { end = toPos; }\n });\n return {start: start, end: end}\n }\n\n var sFrom = range.from(), sTo = range.to();\n if (sFrom.line == sTo.line) {\n drawForLine(sFrom.line, sFrom.ch, sTo.ch);\n } else {\n var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);\n var singleVLine = visualLine(fromLine) == visualLine(toLine);\n var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;\n var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;\n if (singleVLine) {\n if (leftEnd.top < rightStart.top - 2) {\n add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);\n add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);\n } else {\n add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);\n }\n }\n if (leftEnd.bottom < rightStart.top)\n { add(leftSide, leftEnd.bottom, null, rightStart.top); }\n }\n\n output.appendChild(fragment);\n }\n\n // Cursor-blinking\n function restartBlink(cm) {\n if (!cm.state.focused) { return }\n var display = cm.display;\n clearInterval(display.blinker);\n var on = true;\n display.cursorDiv.style.visibility = \"\";\n if (cm.options.cursorBlinkRate > 0)\n { display.blinker = setInterval(function () {\n if (!cm.hasFocus()) { onBlur(cm); }\n display.cursorDiv.style.visibility = (on = !on) ? \"\" : \"hidden\";\n }, cm.options.cursorBlinkRate); }\n else if (cm.options.cursorBlinkRate < 0)\n { display.cursorDiv.style.visibility = \"hidden\"; }\n }\n\n function ensureFocus(cm) {\n if (!cm.hasFocus()) {\n cm.display.input.focus();\n if (!cm.state.focused) { onFocus(cm); }\n }\n }\n\n function delayBlurEvent(cm) {\n cm.state.delayingBlurEvent = true;\n setTimeout(function () { if (cm.state.delayingBlurEvent) {\n cm.state.delayingBlurEvent = false;\n if (cm.state.focused) { onBlur(cm); }\n } }, 100);\n }\n\n function onFocus(cm, e) {\n if (cm.state.delayingBlurEvent && !cm.state.draggingText) { cm.state.delayingBlurEvent = false; }\n\n if (cm.options.readOnly == \"nocursor\") { return }\n if (!cm.state.focused) {\n signal(cm, \"focus\", cm, e);\n cm.state.focused = true;\n addClass(cm.display.wrapper, \"CodeMirror-focused\");\n // This test prevents this from firing when a context\n // menu is closed (since the input reset would kill the\n // select-all detection hack)\n if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {\n cm.display.input.reset();\n if (webkit) { setTimeout(function () { return cm.display.input.reset(true); }, 20); } // Issue #1730\n }\n cm.display.input.receivedFocus();\n }\n restartBlink(cm);\n }\n function onBlur(cm, e) {\n if (cm.state.delayingBlurEvent) { return }\n\n if (cm.state.focused) {\n signal(cm, \"blur\", cm, e);\n cm.state.focused = false;\n rmClass(cm.display.wrapper, \"CodeMirror-focused\");\n }\n clearInterval(cm.display.blinker);\n setTimeout(function () { if (!cm.state.focused) { cm.display.shift = false; } }, 150);\n }\n\n // Read the actual heights of the rendered lines, and update their\n // stored heights to match.\n function updateHeightsInViewport(cm) {\n var display = cm.display;\n var prevBottom = display.lineDiv.offsetTop;\n var viewTop = Math.max(0, display.scroller.getBoundingClientRect().top);\n var oldHeight = display.lineDiv.getBoundingClientRect().top;\n var mustScroll = 0;\n for (var i = 0; i < display.view.length; i++) {\n var cur = display.view[i], wrapping = cm.options.lineWrapping;\n var height = (void 0), width = 0;\n if (cur.hidden) { continue }\n oldHeight += cur.line.height;\n if (ie && ie_version < 8) {\n var bot = cur.node.offsetTop + cur.node.offsetHeight;\n height = bot - prevBottom;\n prevBottom = bot;\n } else {\n var box = cur.node.getBoundingClientRect();\n height = box.bottom - box.top;\n // Check that lines don't extend past the right of the current\n // editor width\n if (!wrapping && cur.text.firstChild)\n { width = cur.text.firstChild.getBoundingClientRect().right - box.left - 1; }\n }\n var diff = cur.line.height - height;\n if (diff > .005 || diff < -.005) {\n if (oldHeight < viewTop) { mustScroll -= diff; }\n updateLineHeight(cur.line, height);\n updateWidgetHeight(cur.line);\n if (cur.rest) { for (var j = 0; j < cur.rest.length; j++)\n { updateWidgetHeight(cur.rest[j]); } }\n }\n if (width > cm.display.sizerWidth) {\n var chWidth = Math.ceil(width / charWidth(cm.display));\n if (chWidth > cm.display.maxLineLength) {\n cm.display.maxLineLength = chWidth;\n cm.display.maxLine = cur.line;\n cm.display.maxLineChanged = true;\n }\n }\n }\n if (Math.abs(mustScroll) > 2) { display.scroller.scrollTop += mustScroll; }\n }\n\n // Read and store the height of line widgets associated with the\n // given line.\n function updateWidgetHeight(line) {\n if (line.widgets) { for (var i = 0; i < line.widgets.length; ++i) {\n var w = line.widgets[i], parent = w.node.parentNode;\n if (parent) { w.height = parent.offsetHeight; }\n } }\n }\n\n // Compute the lines that are visible in a given viewport (defaults\n // the the current scroll position). viewport may contain top,\n // height, and ensure (see op.scrollToPos) properties.\n function visibleLines(display, doc, viewport) {\n var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop;\n top = Math.floor(top - paddingTop(display));\n var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight;\n\n var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom);\n // Ensure is a {from: {line, ch}, to: {line, ch}} object, and\n // forces those lines into the viewport (if possible).\n if (viewport && viewport.ensure) {\n var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line;\n if (ensureFrom < from) {\n from = ensureFrom;\n to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight);\n } else if (Math.min(ensureTo, doc.lastLine()) >= to) {\n from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight);\n to = ensureTo;\n }\n }\n return {from: from, to: Math.max(to, from + 1)}\n }\n\n // SCROLLING THINGS INTO VIEW\n\n // If an editor sits on the top or bottom of the window, partially\n // scrolled out of view, this ensures that the cursor is visible.\n function maybeScrollWindow(cm, rect) {\n if (signalDOMEvent(cm, \"scrollCursorIntoView\")) { return }\n\n var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;\n var doc = display.wrapper.ownerDocument;\n if (rect.top + box.top < 0) { doScroll = true; }\n else if (rect.bottom + box.top > (doc.defaultView.innerHeight || doc.documentElement.clientHeight)) { doScroll = false; }\n if (doScroll != null && !phantom) {\n var scrollNode = elt(\"div\", \"\\u200b\", null, (\"position: absolute;\\n top: \" + (rect.top - display.viewOffset - paddingTop(cm.display)) + \"px;\\n height: \" + (rect.bottom - rect.top + scrollGap(cm) + display.barHeight) + \"px;\\n left: \" + (rect.left) + \"px; width: \" + (Math.max(2, rect.right - rect.left)) + \"px;\"));\n cm.display.lineSpace.appendChild(scrollNode);\n scrollNode.scrollIntoView(doScroll);\n cm.display.lineSpace.removeChild(scrollNode);\n }\n }\n\n // Scroll a given position into view (immediately), verifying that\n // it actually became visible (as line heights are accurately\n // measured, the position of something may 'drift' during drawing).\n function scrollPosIntoView(cm, pos, end, margin) {\n if (margin == null) { margin = 0; }\n var rect;\n if (!cm.options.lineWrapping && pos == end) {\n // Set pos and end to the cursor positions around the character pos sticks to\n // If pos.sticky == \"before\", that is around pos.ch - 1, otherwise around pos.ch\n // If pos == Pos(_, 0, \"before\"), pos and end are unchanged\n end = pos.sticky == \"before\" ? Pos(pos.line, pos.ch + 1, \"before\") : pos;\n pos = pos.ch ? Pos(pos.line, pos.sticky == \"before\" ? pos.ch - 1 : pos.ch, \"after\") : pos;\n }\n for (var limit = 0; limit < 5; limit++) {\n var changed = false;\n var coords = cursorCoords(cm, pos);\n var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);\n rect = {left: Math.min(coords.left, endCoords.left),\n top: Math.min(coords.top, endCoords.top) - margin,\n right: Math.max(coords.left, endCoords.left),\n bottom: Math.max(coords.bottom, endCoords.bottom) + margin};\n var scrollPos = calculateScrollPos(cm, rect);\n var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;\n if (scrollPos.scrollTop != null) {\n updateScrollTop(cm, scrollPos.scrollTop);\n if (Math.abs(cm.doc.scrollTop - startTop) > 1) { changed = true; }\n }\n if (scrollPos.scrollLeft != null) {\n setScrollLeft(cm, scrollPos.scrollLeft);\n if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) { changed = true; }\n }\n if (!changed) { break }\n }\n return rect\n }\n\n // Scroll a given set of coordinates into view (immediately).\n function scrollIntoView(cm, rect) {\n var scrollPos = calculateScrollPos(cm, rect);\n if (scrollPos.scrollTop != null) { updateScrollTop(cm, scrollPos.scrollTop); }\n if (scrollPos.scrollLeft != null) { setScrollLeft(cm, scrollPos.scrollLeft); }\n }\n\n // Calculate a new scroll position needed to scroll the given\n // rectangle into view. Returns an object with scrollTop and\n // scrollLeft properties. When these are undefined, the\n // vertical/horizontal position does not need to be adjusted.\n function calculateScrollPos(cm, rect) {\n var display = cm.display, snapMargin = textHeight(cm.display);\n if (rect.top < 0) { rect.top = 0; }\n var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;\n var screen = displayHeight(cm), result = {};\n if (rect.bottom - rect.top > screen) { rect.bottom = rect.top + screen; }\n var docBottom = cm.doc.height + paddingVert(display);\n var atTop = rect.top < snapMargin, atBottom = rect.bottom > docBottom - snapMargin;\n if (rect.top < screentop) {\n result.scrollTop = atTop ? 0 : rect.top;\n } else if (rect.bottom > screentop + screen) {\n var newTop = Math.min(rect.top, (atBottom ? docBottom : rect.bottom) - screen);\n if (newTop != screentop) { result.scrollTop = newTop; }\n }\n\n var gutterSpace = cm.options.fixedGutter ? 0 : display.gutters.offsetWidth;\n var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft - gutterSpace;\n var screenw = displayWidth(cm) - display.gutters.offsetWidth;\n var tooWide = rect.right - rect.left > screenw;\n if (tooWide) { rect.right = rect.left + screenw; }\n if (rect.left < 10)\n { result.scrollLeft = 0; }\n else if (rect.left < screenleft)\n { result.scrollLeft = Math.max(0, rect.left + gutterSpace - (tooWide ? 0 : 10)); }\n else if (rect.right > screenw + screenleft - 3)\n { result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw; }\n return result\n }\n\n // Store a relative adjustment to the scroll position in the current\n // operation (to be applied when the operation finishes).\n function addToScrollTop(cm, top) {\n if (top == null) { return }\n resolveScrollToPos(cm);\n cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;\n }\n\n // Make sure that at the end of the operation the current cursor is\n // shown.\n function ensureCursorVisible(cm) {\n resolveScrollToPos(cm);\n var cur = cm.getCursor();\n cm.curOp.scrollToPos = {from: cur, to: cur, margin: cm.options.cursorScrollMargin};\n }\n\n function scrollToCoords(cm, x, y) {\n if (x != null || y != null) { resolveScrollToPos(cm); }\n if (x != null) { cm.curOp.scrollLeft = x; }\n if (y != null) { cm.curOp.scrollTop = y; }\n }\n\n function scrollToRange(cm, range) {\n resolveScrollToPos(cm);\n cm.curOp.scrollToPos = range;\n }\n\n // When an operation has its scrollToPos property set, and another\n // scroll action is applied before the end of the operation, this\n // 'simulates' scrolling that position into view in a cheap way, so\n // that the effect of intermediate scroll commands is not ignored.\n function resolveScrollToPos(cm) {\n var range = cm.curOp.scrollToPos;\n if (range) {\n cm.curOp.scrollToPos = null;\n var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to);\n scrollToCoordsRange(cm, from, to, range.margin);\n }\n }\n\n function scrollToCoordsRange(cm, from, to, margin) {\n var sPos = calculateScrollPos(cm, {\n left: Math.min(from.left, to.left),\n top: Math.min(from.top, to.top) - margin,\n right: Math.max(from.right, to.right),\n bottom: Math.max(from.bottom, to.bottom) + margin\n });\n scrollToCoords(cm, sPos.scrollLeft, sPos.scrollTop);\n }\n\n // Sync the scrollable area and scrollbars, ensure the viewport\n // covers the visible area.\n function updateScrollTop(cm, val) {\n if (Math.abs(cm.doc.scrollTop - val) < 2) { return }\n if (!gecko) { updateDisplaySimple(cm, {top: val}); }\n setScrollTop(cm, val, true);\n if (gecko) { updateDisplaySimple(cm); }\n startWorker(cm, 100);\n }\n\n function setScrollTop(cm, val, forceScroll) {\n val = Math.max(0, Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, val));\n if (cm.display.scroller.scrollTop == val && !forceScroll) { return }\n cm.doc.scrollTop = val;\n cm.display.scrollbars.setScrollTop(val);\n if (cm.display.scroller.scrollTop != val) { cm.display.scroller.scrollTop = val; }\n }\n\n // Sync scroller and scrollbar, ensure the gutter elements are\n // aligned.\n function setScrollLeft(cm, val, isScroller, forceScroll) {\n val = Math.max(0, Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth));\n if ((isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) && !forceScroll) { return }\n cm.doc.scrollLeft = val;\n alignHorizontally(cm);\n if (cm.display.scroller.scrollLeft != val) { cm.display.scroller.scrollLeft = val; }\n cm.display.scrollbars.setScrollLeft(val);\n }\n\n // SCROLLBARS\n\n // Prepare DOM reads needed to update the scrollbars. Done in one\n // shot to minimize update/measure roundtrips.\n function measureForScrollbars(cm) {\n var d = cm.display, gutterW = d.gutters.offsetWidth;\n var docH = Math.round(cm.doc.height + paddingVert(cm.display));\n return {\n clientHeight: d.scroller.clientHeight,\n viewHeight: d.wrapper.clientHeight,\n scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,\n viewWidth: d.wrapper.clientWidth,\n barLeft: cm.options.fixedGutter ? gutterW : 0,\n docHeight: docH,\n scrollHeight: docH + scrollGap(cm) + d.barHeight,\n nativeBarWidth: d.nativeBarWidth,\n gutterWidth: gutterW\n }\n }\n\n var NativeScrollbars = function(place, scroll, cm) {\n this.cm = cm;\n var vert = this.vert = elt(\"div\", [elt(\"div\", null, null, \"min-width: 1px\")], \"CodeMirror-vscrollbar\");\n var horiz = this.horiz = elt(\"div\", [elt(\"div\", null, null, \"height: 100%; min-height: 1px\")], \"CodeMirror-hscrollbar\");\n vert.tabIndex = horiz.tabIndex = -1;\n place(vert); place(horiz);\n\n on(vert, \"scroll\", function () {\n if (vert.clientHeight) { scroll(vert.scrollTop, \"vertical\"); }\n });\n on(horiz, \"scroll\", function () {\n if (horiz.clientWidth) { scroll(horiz.scrollLeft, \"horizontal\"); }\n });\n\n this.checkedZeroWidth = false;\n // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).\n if (ie && ie_version < 8) { this.horiz.style.minHeight = this.vert.style.minWidth = \"18px\"; }\n };\n\n NativeScrollbars.prototype.update = function (measure) {\n var needsH = measure.scrollWidth > measure.clientWidth + 1;\n var needsV = measure.scrollHeight > measure.clientHeight + 1;\n var sWidth = measure.nativeBarWidth;\n\n if (needsV) {\n this.vert.style.display = \"block\";\n this.vert.style.bottom = needsH ? sWidth + \"px\" : \"0\";\n var totalHeight = measure.viewHeight - (needsH ? sWidth : 0);\n // A bug in IE8 can cause this value to be negative, so guard it.\n this.vert.firstChild.style.height =\n Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + \"px\";\n } else {\n this.vert.scrollTop = 0;\n this.vert.style.display = \"\";\n this.vert.firstChild.style.height = \"0\";\n }\n\n if (needsH) {\n this.horiz.style.display = \"block\";\n this.horiz.style.right = needsV ? sWidth + \"px\" : \"0\";\n this.horiz.style.left = measure.barLeft + \"px\";\n var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0);\n this.horiz.firstChild.style.width =\n Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + \"px\";\n } else {\n this.horiz.style.display = \"\";\n this.horiz.firstChild.style.width = \"0\";\n }\n\n if (!this.checkedZeroWidth && measure.clientHeight > 0) {\n if (sWidth == 0) { this.zeroWidthHack(); }\n this.checkedZeroWidth = true;\n }\n\n return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0}\n };\n\n NativeScrollbars.prototype.setScrollLeft = function (pos) {\n if (this.horiz.scrollLeft != pos) { this.horiz.scrollLeft = pos; }\n if (this.disableHoriz) { this.enableZeroWidthBar(this.horiz, this.disableHoriz, \"horiz\"); }\n };\n\n NativeScrollbars.prototype.setScrollTop = function (pos) {\n if (this.vert.scrollTop != pos) { this.vert.scrollTop = pos; }\n if (this.disableVert) { this.enableZeroWidthBar(this.vert, this.disableVert, \"vert\"); }\n };\n\n NativeScrollbars.prototype.zeroWidthHack = function () {\n var w = mac && !mac_geMountainLion ? \"12px\" : \"18px\";\n this.horiz.style.height = this.vert.style.width = w;\n this.horiz.style.visibility = this.vert.style.visibility = \"hidden\";\n this.disableHoriz = new Delayed;\n this.disableVert = new Delayed;\n };\n\n NativeScrollbars.prototype.enableZeroWidthBar = function (bar, delay, type) {\n bar.style.visibility = \"\";\n function maybeDisable() {\n // To find out whether the scrollbar is still visible, we\n // check whether the element under the pixel in the bottom\n // right corner of the scrollbar box is the scrollbar box\n // itself (when the bar is still visible) or its filler child\n // (when the bar is hidden). If it is still visible, we keep\n // it enabled, if it's hidden, we disable pointer events.\n var box = bar.getBoundingClientRect();\n var elt = type == \"vert\" ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2)\n : document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1);\n if (elt != bar) { bar.style.visibility = \"hidden\"; }\n else { delay.set(1000, maybeDisable); }\n }\n delay.set(1000, maybeDisable);\n };\n\n NativeScrollbars.prototype.clear = function () {\n var parent = this.horiz.parentNode;\n parent.removeChild(this.horiz);\n parent.removeChild(this.vert);\n };\n\n var NullScrollbars = function () {};\n\n NullScrollbars.prototype.update = function () { return {bottom: 0, right: 0} };\n NullScrollbars.prototype.setScrollLeft = function () {};\n NullScrollbars.prototype.setScrollTop = function () {};\n NullScrollbars.prototype.clear = function () {};\n\n function updateScrollbars(cm, measure) {\n if (!measure) { measure = measureForScrollbars(cm); }\n var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight;\n updateScrollbarsInner(cm, measure);\n for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {\n if (startWidth != cm.display.barWidth && cm.options.lineWrapping)\n { updateHeightsInViewport(cm); }\n updateScrollbarsInner(cm, measureForScrollbars(cm));\n startWidth = cm.display.barWidth; startHeight = cm.display.barHeight;\n }\n }\n\n // Re-synchronize the fake scrollbars with the actual size of the\n // content.\n function updateScrollbarsInner(cm, measure) {\n var d = cm.display;\n var sizes = d.scrollbars.update(measure);\n\n d.sizer.style.paddingRight = (d.barWidth = sizes.right) + \"px\";\n d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + \"px\";\n d.heightForcer.style.borderBottom = sizes.bottom + \"px solid transparent\";\n\n if (sizes.right && sizes.bottom) {\n d.scrollbarFiller.style.display = \"block\";\n d.scrollbarFiller.style.height = sizes.bottom + \"px\";\n d.scrollbarFiller.style.width = sizes.right + \"px\";\n } else { d.scrollbarFiller.style.display = \"\"; }\n if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {\n d.gutterFiller.style.display = \"block\";\n d.gutterFiller.style.height = sizes.bottom + \"px\";\n d.gutterFiller.style.width = measure.gutterWidth + \"px\";\n } else { d.gutterFiller.style.display = \"\"; }\n }\n\n var scrollbarModel = {\"native\": NativeScrollbars, \"null\": NullScrollbars};\n\n function initScrollbars(cm) {\n if (cm.display.scrollbars) {\n cm.display.scrollbars.clear();\n if (cm.display.scrollbars.addClass)\n { rmClass(cm.display.wrapper, cm.display.scrollbars.addClass); }\n }\n\n cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function (node) {\n cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller);\n // Prevent clicks in the scrollbars from killing focus\n on(node, \"mousedown\", function () {\n if (cm.state.focused) { setTimeout(function () { return cm.display.input.focus(); }, 0); }\n });\n node.setAttribute(\"cm-not-content\", \"true\");\n }, function (pos, axis) {\n if (axis == \"horizontal\") { setScrollLeft(cm, pos); }\n else { updateScrollTop(cm, pos); }\n }, cm);\n if (cm.display.scrollbars.addClass)\n { addClass(cm.display.wrapper, cm.display.scrollbars.addClass); }\n }\n\n // Operations are used to wrap a series of changes to the editor\n // state in such a way that each change won't have to update the\n // cursor and display (which would be awkward, slow, and\n // error-prone). Instead, display updates are batched and then all\n // combined and executed at once.\n\n var nextOpId = 0;\n // Start a new operation.\n function startOperation(cm) {\n cm.curOp = {\n cm: cm,\n viewChanged: false, // Flag that indicates that lines might need to be redrawn\n startHeight: cm.doc.height, // Used to detect need to update scrollbar\n forceUpdate: false, // Used to force a redraw\n updateInput: 0, // Whether to reset the input textarea\n typing: false, // Whether this reset should be careful to leave existing text (for compositing)\n changeObjs: null, // Accumulated changes, for firing change events\n cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on\n cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already\n selectionChanged: false, // Whether the selection needs to be redrawn\n updateMaxLine: false, // Set when the widest line needs to be determined anew\n scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet\n scrollToPos: null, // Used to scroll to a specific position\n focus: false,\n id: ++nextOpId, // Unique ID\n markArrays: null // Used by addMarkedSpan\n };\n pushOperation(cm.curOp);\n }\n\n // Finish an operation, updating the display and signalling delayed events\n function endOperation(cm) {\n var op = cm.curOp;\n if (op) { finishOperation(op, function (group) {\n for (var i = 0; i < group.ops.length; i++)\n { group.ops[i].cm.curOp = null; }\n endOperations(group);\n }); }\n }\n\n // The DOM updates done when an operation finishes are batched so\n // that the minimum number of relayouts are required.\n function endOperations(group) {\n var ops = group.ops;\n for (var i = 0; i < ops.length; i++) // Read DOM\n { endOperation_R1(ops[i]); }\n for (var i$1 = 0; i$1 < ops.length; i$1++) // Write DOM (maybe)\n { endOperation_W1(ops[i$1]); }\n for (var i$2 = 0; i$2 < ops.length; i$2++) // Read DOM\n { endOperation_R2(ops[i$2]); }\n for (var i$3 = 0; i$3 < ops.length; i$3++) // Write DOM (maybe)\n { endOperation_W2(ops[i$3]); }\n for (var i$4 = 0; i$4 < ops.length; i$4++) // Read DOM\n { endOperation_finish(ops[i$4]); }\n }\n\n function endOperation_R1(op) {\n var cm = op.cm, display = cm.display;\n maybeClipScrollbars(cm);\n if (op.updateMaxLine) { findMaxLine(cm); }\n\n op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||\n op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||\n op.scrollToPos.to.line >= display.viewTo) ||\n display.maxLineChanged && cm.options.lineWrapping;\n op.update = op.mustUpdate &&\n new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate);\n }\n\n function endOperation_W1(op) {\n op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update);\n }\n\n function endOperation_R2(op) {\n var cm = op.cm, display = cm.display;\n if (op.updatedDisplay) { updateHeightsInViewport(cm); }\n\n op.barMeasure = measureForScrollbars(cm);\n\n // If the max line changed since it was last measured, measure it,\n // and ensure the document's width matches it.\n // updateDisplay_W2 will use these properties to do the actual resizing\n if (display.maxLineChanged && !cm.options.lineWrapping) {\n op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3;\n cm.display.sizerWidth = op.adjustWidthTo;\n op.barMeasure.scrollWidth =\n Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth);\n op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm));\n }\n\n if (op.updatedDisplay || op.selectionChanged)\n { op.preparedSelection = display.input.prepareSelection(); }\n }\n\n function endOperation_W2(op) {\n var cm = op.cm;\n\n if (op.adjustWidthTo != null) {\n cm.display.sizer.style.minWidth = op.adjustWidthTo + \"px\";\n if (op.maxScrollLeft < cm.doc.scrollLeft)\n { setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true); }\n cm.display.maxLineChanged = false;\n }\n\n var takeFocus = op.focus && op.focus == activeElt(doc(cm));\n if (op.preparedSelection)\n { cm.display.input.showSelection(op.preparedSelection, takeFocus); }\n if (op.updatedDisplay || op.startHeight != cm.doc.height)\n { updateScrollbars(cm, op.barMeasure); }\n if (op.updatedDisplay)\n { setDocumentHeight(cm, op.barMeasure); }\n\n if (op.selectionChanged) { restartBlink(cm); }\n\n if (cm.state.focused && op.updateInput)\n { cm.display.input.reset(op.typing); }\n if (takeFocus) { ensureFocus(op.cm); }\n }\n\n function endOperation_finish(op) {\n var cm = op.cm, display = cm.display, doc = cm.doc;\n\n if (op.updatedDisplay) { postUpdateDisplay(cm, op.update); }\n\n // Abort mouse wheel delta measurement, when scrolling explicitly\n if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))\n { display.wheelStartX = display.wheelStartY = null; }\n\n // Propagate the scroll position to the actual DOM scroller\n if (op.scrollTop != null) { setScrollTop(cm, op.scrollTop, op.forceScroll); }\n\n if (op.scrollLeft != null) { setScrollLeft(cm, op.scrollLeft, true, true); }\n // If we need to scroll a specific position into view, do so.\n if (op.scrollToPos) {\n var rect = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),\n clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin);\n maybeScrollWindow(cm, rect);\n }\n\n // Fire events for markers that are hidden/unidden by editing or\n // undoing\n var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;\n if (hidden) { for (var i = 0; i < hidden.length; ++i)\n { if (!hidden[i].lines.length) { signal(hidden[i], \"hide\"); } } }\n if (unhidden) { for (var i$1 = 0; i$1 < unhidden.length; ++i$1)\n { if (unhidden[i$1].lines.length) { signal(unhidden[i$1], \"unhide\"); } } }\n\n if (display.wrapper.offsetHeight)\n { doc.scrollTop = cm.display.scroller.scrollTop; }\n\n // Fire change events, and delayed event handlers\n if (op.changeObjs)\n { signal(cm, \"changes\", cm, op.changeObjs); }\n if (op.update)\n { op.update.finish(); }\n }\n\n // Run the given function in an operation\n function runInOp(cm, f) {\n if (cm.curOp) { return f() }\n startOperation(cm);\n try { return f() }\n finally { endOperation(cm); }\n }\n // Wraps a function in an operation. Returns the wrapped function.\n function operation(cm, f) {\n return function() {\n if (cm.curOp) { return f.apply(cm, arguments) }\n startOperation(cm);\n try { return f.apply(cm, arguments) }\n finally { endOperation(cm); }\n }\n }\n // Used to add methods to editor and doc instances, wrapping them in\n // operations.\n function methodOp(f) {\n return function() {\n if (this.curOp) { return f.apply(this, arguments) }\n startOperation(this);\n try { return f.apply(this, arguments) }\n finally { endOperation(this); }\n }\n }\n function docMethodOp(f) {\n return function() {\n var cm = this.cm;\n if (!cm || cm.curOp) { return f.apply(this, arguments) }\n startOperation(cm);\n try { return f.apply(this, arguments) }\n finally { endOperation(cm); }\n }\n }\n\n // HIGHLIGHT WORKER\n\n function startWorker(cm, time) {\n if (cm.doc.highlightFrontier < cm.display.viewTo)\n { cm.state.highlight.set(time, bind(highlightWorker, cm)); }\n }\n\n function highlightWorker(cm) {\n var doc = cm.doc;\n if (doc.highlightFrontier >= cm.display.viewTo) { return }\n var end = +new Date + cm.options.workTime;\n var context = getContextBefore(cm, doc.highlightFrontier);\n var changedLines = [];\n\n doc.iter(context.line, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) {\n if (context.line >= cm.display.viewFrom) { // Visible\n var oldStyles = line.styles;\n var resetState = line.text.length > cm.options.maxHighlightLength ? copyState(doc.mode, context.state) : null;\n var highlighted = highlightLine(cm, line, context, true);\n if (resetState) { context.state = resetState; }\n line.styles = highlighted.styles;\n var oldCls = line.styleClasses, newCls = highlighted.classes;\n if (newCls) { line.styleClasses = newCls; }\n else if (oldCls) { line.styleClasses = null; }\n var ischange = !oldStyles || oldStyles.length != line.styles.length ||\n oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass);\n for (var i = 0; !ischange && i < oldStyles.length; ++i) { ischange = oldStyles[i] != line.styles[i]; }\n if (ischange) { changedLines.push(context.line); }\n line.stateAfter = context.save();\n context.nextLine();\n } else {\n if (line.text.length <= cm.options.maxHighlightLength)\n { processLine(cm, line.text, context); }\n line.stateAfter = context.line % 5 == 0 ? context.save() : null;\n context.nextLine();\n }\n if (+new Date > end) {\n startWorker(cm, cm.options.workDelay);\n return true\n }\n });\n doc.highlightFrontier = context.line;\n doc.modeFrontier = Math.max(doc.modeFrontier, context.line);\n if (changedLines.length) { runInOp(cm, function () {\n for (var i = 0; i < changedLines.length; i++)\n { regLineChange(cm, changedLines[i], \"text\"); }\n }); }\n }\n\n // DISPLAY DRAWING\n\n var DisplayUpdate = function(cm, viewport, force) {\n var display = cm.display;\n\n this.viewport = viewport;\n // Store some values that we'll need later (but don't want to force a relayout for)\n this.visible = visibleLines(display, cm.doc, viewport);\n this.editorIsHidden = !display.wrapper.offsetWidth;\n this.wrapperHeight = display.wrapper.clientHeight;\n this.wrapperWidth = display.wrapper.clientWidth;\n this.oldDisplayWidth = displayWidth(cm);\n this.force = force;\n this.dims = getDimensions(cm);\n this.events = [];\n };\n\n DisplayUpdate.prototype.signal = function (emitter, type) {\n if (hasHandler(emitter, type))\n { this.events.push(arguments); }\n };\n DisplayUpdate.prototype.finish = function () {\n for (var i = 0; i < this.events.length; i++)\n { signal.apply(null, this.events[i]); }\n };\n\n function maybeClipScrollbars(cm) {\n var display = cm.display;\n if (!display.scrollbarsClipped && display.scroller.offsetWidth) {\n display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth;\n display.heightForcer.style.height = scrollGap(cm) + \"px\";\n display.sizer.style.marginBottom = -display.nativeBarWidth + \"px\";\n display.sizer.style.borderRightWidth = scrollGap(cm) + \"px\";\n display.scrollbarsClipped = true;\n }\n }\n\n function selectionSnapshot(cm) {\n if (cm.hasFocus()) { return null }\n var active = activeElt(doc(cm));\n if (!active || !contains(cm.display.lineDiv, active)) { return null }\n var result = {activeElt: active};\n if (window.getSelection) {\n var sel = win(cm).getSelection();\n if (sel.anchorNode && sel.extend && contains(cm.display.lineDiv, sel.anchorNode)) {\n result.anchorNode = sel.anchorNode;\n result.anchorOffset = sel.anchorOffset;\n result.focusNode = sel.focusNode;\n result.focusOffset = sel.focusOffset;\n }\n }\n return result\n }\n\n function restoreSelection(snapshot) {\n if (!snapshot || !snapshot.activeElt || snapshot.activeElt == activeElt(snapshot.activeElt.ownerDocument)) { return }\n snapshot.activeElt.focus();\n if (!/^(INPUT|TEXTAREA)$/.test(snapshot.activeElt.nodeName) &&\n snapshot.anchorNode && contains(document.body, snapshot.anchorNode) && contains(document.body, snapshot.focusNode)) {\n var doc = snapshot.activeElt.ownerDocument;\n var sel = doc.defaultView.getSelection(), range = doc.createRange();\n range.setEnd(snapshot.anchorNode, snapshot.anchorOffset);\n range.collapse(false);\n sel.removeAllRanges();\n sel.addRange(range);\n sel.extend(snapshot.focusNode, snapshot.focusOffset);\n }\n }\n\n // Does the actual updating of the line display. Bails out\n // (returning false) when there is nothing to be done and forced is\n // false.\n function updateDisplayIfNeeded(cm, update) {\n var display = cm.display, doc = cm.doc;\n\n if (update.editorIsHidden) {\n resetView(cm);\n return false\n }\n\n // Bail out if the visible area is already rendered and nothing changed.\n if (!update.force &&\n update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo &&\n (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&\n display.renderedView == display.view && countDirtyView(cm) == 0)\n { return false }\n\n if (maybeUpdateLineNumberWidth(cm)) {\n resetView(cm);\n update.dims = getDimensions(cm);\n }\n\n // Compute a suitable new viewport (from & to)\n var end = doc.first + doc.size;\n var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first);\n var to = Math.min(end, update.visible.to + cm.options.viewportMargin);\n if (display.viewFrom < from && from - display.viewFrom < 20) { from = Math.max(doc.first, display.viewFrom); }\n if (display.viewTo > to && display.viewTo - to < 20) { to = Math.min(end, display.viewTo); }\n if (sawCollapsedSpans) {\n from = visualLineNo(cm.doc, from);\n to = visualLineEndNo(cm.doc, to);\n }\n\n var different = from != display.viewFrom || to != display.viewTo ||\n display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth;\n adjustView(cm, from, to);\n\n display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom));\n // Position the mover div to align with the current scroll position\n cm.display.mover.style.top = display.viewOffset + \"px\";\n\n var toUpdate = countDirtyView(cm);\n if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view &&\n (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo))\n { return false }\n\n // For big changes, we hide the enclosing element during the\n // update, since that speeds up the operations on most browsers.\n var selSnapshot = selectionSnapshot(cm);\n if (toUpdate > 4) { display.lineDiv.style.display = \"none\"; }\n patchDisplay(cm, display.updateLineNumbers, update.dims);\n if (toUpdate > 4) { display.lineDiv.style.display = \"\"; }\n display.renderedView = display.view;\n // There might have been a widget with a focused element that got\n // hidden or updated, if so re-focus it.\n restoreSelection(selSnapshot);\n\n // Prevent selection and cursors from interfering with the scroll\n // width and height.\n removeChildren(display.cursorDiv);\n removeChildren(display.selectionDiv);\n display.gutters.style.height = display.sizer.style.minHeight = 0;\n\n if (different) {\n display.lastWrapHeight = update.wrapperHeight;\n display.lastWrapWidth = update.wrapperWidth;\n startWorker(cm, 400);\n }\n\n display.updateLineNumbers = null;\n\n return true\n }\n\n function postUpdateDisplay(cm, update) {\n var viewport = update.viewport;\n\n for (var first = true;; first = false) {\n if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) {\n // Clip forced viewport to actual scrollable area.\n if (viewport && viewport.top != null)\n { viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)}; }\n // Updated line heights might result in the drawn area not\n // actually covering the viewport. Keep looping until it does.\n update.visible = visibleLines(cm.display, cm.doc, viewport);\n if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo)\n { break }\n } else if (first) {\n update.visible = visibleLines(cm.display, cm.doc, viewport);\n }\n if (!updateDisplayIfNeeded(cm, update)) { break }\n updateHeightsInViewport(cm);\n var barMeasure = measureForScrollbars(cm);\n updateSelection(cm);\n updateScrollbars(cm, barMeasure);\n setDocumentHeight(cm, barMeasure);\n update.force = false;\n }\n\n update.signal(cm, \"update\", cm);\n if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {\n update.signal(cm, \"viewportChange\", cm, cm.display.viewFrom, cm.display.viewTo);\n cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo;\n }\n }\n\n function updateDisplaySimple(cm, viewport) {\n var update = new DisplayUpdate(cm, viewport);\n if (updateDisplayIfNeeded(cm, update)) {\n updateHeightsInViewport(cm);\n postUpdateDisplay(cm, update);\n var barMeasure = measureForScrollbars(cm);\n updateSelection(cm);\n updateScrollbars(cm, barMeasure);\n setDocumentHeight(cm, barMeasure);\n update.finish();\n }\n }\n\n // Sync the actual display DOM structure with display.view, removing\n // nodes for lines that are no longer in view, and creating the ones\n // that are not there yet, and updating the ones that are out of\n // date.\n function patchDisplay(cm, updateNumbersFrom, dims) {\n var display = cm.display, lineNumbers = cm.options.lineNumbers;\n var container = display.lineDiv, cur = container.firstChild;\n\n function rm(node) {\n var next = node.nextSibling;\n // Works around a throw-scroll bug in OS X Webkit\n if (webkit && mac && cm.display.currentWheelTarget == node)\n { node.style.display = \"none\"; }\n else\n { node.parentNode.removeChild(node); }\n return next\n }\n\n var view = display.view, lineN = display.viewFrom;\n // Loop over the elements in the view, syncing cur (the DOM nodes\n // in display.lineDiv) with the view as we go.\n for (var i = 0; i < view.length; i++) {\n var lineView = view[i];\n if (lineView.hidden) ; else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet\n var node = buildLineElement(cm, lineView, lineN, dims);\n container.insertBefore(node, cur);\n } else { // Already drawn\n while (cur != lineView.node) { cur = rm(cur); }\n var updateNumber = lineNumbers && updateNumbersFrom != null &&\n updateNumbersFrom <= lineN && lineView.lineNumber;\n if (lineView.changes) {\n if (indexOf(lineView.changes, \"gutter\") > -1) { updateNumber = false; }\n updateLineForChanges(cm, lineView, lineN, dims);\n }\n if (updateNumber) {\n removeChildren(lineView.lineNumber);\n lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));\n }\n cur = lineView.node.nextSibling;\n }\n lineN += lineView.size;\n }\n while (cur) { cur = rm(cur); }\n }\n\n function updateGutterSpace(display) {\n var width = display.gutters.offsetWidth;\n display.sizer.style.marginLeft = width + \"px\";\n // Send an event to consumers responding to changes in gutter width.\n signalLater(display, \"gutterChanged\", display);\n }\n\n function setDocumentHeight(cm, measure) {\n cm.display.sizer.style.minHeight = measure.docHeight + \"px\";\n cm.display.heightForcer.style.top = measure.docHeight + \"px\";\n cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + \"px\";\n }\n\n // Re-align line numbers and gutter marks to compensate for\n // horizontal scrolling.\n function alignHorizontally(cm) {\n var display = cm.display, view = display.view;\n if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) { return }\n var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;\n var gutterW = display.gutters.offsetWidth, left = comp + \"px\";\n for (var i = 0; i < view.length; i++) { if (!view[i].hidden) {\n if (cm.options.fixedGutter) {\n if (view[i].gutter)\n { view[i].gutter.style.left = left; }\n if (view[i].gutterBackground)\n { view[i].gutterBackground.style.left = left; }\n }\n var align = view[i].alignable;\n if (align) { for (var j = 0; j < align.length; j++)\n { align[j].style.left = left; } }\n } }\n if (cm.options.fixedGutter)\n { display.gutters.style.left = (comp + gutterW) + \"px\"; }\n }\n\n // Used to ensure that the line number gutter is still the right\n // size for the current document size. Returns true when an update\n // is needed.\n function maybeUpdateLineNumberWidth(cm) {\n if (!cm.options.lineNumbers) { return false }\n var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;\n if (last.length != display.lineNumChars) {\n var test = display.measure.appendChild(elt(\"div\", [elt(\"div\", last)],\n \"CodeMirror-linenumber CodeMirror-gutter-elt\"));\n var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;\n display.lineGutter.style.width = \"\";\n display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1;\n display.lineNumWidth = display.lineNumInnerWidth + padding;\n display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;\n display.lineGutter.style.width = display.lineNumWidth + \"px\";\n updateGutterSpace(cm.display);\n return true\n }\n return false\n }\n\n function getGutters(gutters, lineNumbers) {\n var result = [], sawLineNumbers = false;\n for (var i = 0; i < gutters.length; i++) {\n var name = gutters[i], style = null;\n if (typeof name != \"string\") { style = name.style; name = name.className; }\n if (name == \"CodeMirror-linenumbers\") {\n if (!lineNumbers) { continue }\n else { sawLineNumbers = true; }\n }\n result.push({className: name, style: style});\n }\n if (lineNumbers && !sawLineNumbers) { result.push({className: \"CodeMirror-linenumbers\", style: null}); }\n return result\n }\n\n // Rebuild the gutter elements, ensure the margin to the left of the\n // code matches their width.\n function renderGutters(display) {\n var gutters = display.gutters, specs = display.gutterSpecs;\n removeChildren(gutters);\n display.lineGutter = null;\n for (var i = 0; i < specs.length; ++i) {\n var ref = specs[i];\n var className = ref.className;\n var style = ref.style;\n var gElt = gutters.appendChild(elt(\"div\", null, \"CodeMirror-gutter \" + className));\n if (style) { gElt.style.cssText = style; }\n if (className == \"CodeMirror-linenumbers\") {\n display.lineGutter = gElt;\n gElt.style.width = (display.lineNumWidth || 1) + \"px\";\n }\n }\n gutters.style.display = specs.length ? \"\" : \"none\";\n updateGutterSpace(display);\n }\n\n function updateGutters(cm) {\n renderGutters(cm.display);\n regChange(cm);\n alignHorizontally(cm);\n }\n\n // The display handles the DOM integration, both for input reading\n // and content drawing. It holds references to DOM nodes and\n // display-related state.\n\n function Display(place, doc, input, options) {\n var d = this;\n this.input = input;\n\n // Covers bottom-right square when both scrollbars are present.\n d.scrollbarFiller = elt(\"div\", null, \"CodeMirror-scrollbar-filler\");\n d.scrollbarFiller.setAttribute(\"cm-not-content\", \"true\");\n // Covers bottom of gutter when coverGutterNextToScrollbar is on\n // and h scrollbar is present.\n d.gutterFiller = elt(\"div\", null, \"CodeMirror-gutter-filler\");\n d.gutterFiller.setAttribute(\"cm-not-content\", \"true\");\n // Will contain the actual code, positioned to cover the viewport.\n d.lineDiv = eltP(\"div\", null, \"CodeMirror-code\");\n // Elements are added to these to represent selection and cursors.\n d.selectionDiv = elt(\"div\", null, null, \"position: relative; z-index: 1\");\n d.cursorDiv = elt(\"div\", null, \"CodeMirror-cursors\");\n // A visibility: hidden element used to find the size of things.\n d.measure = elt(\"div\", null, \"CodeMirror-measure\");\n // When lines outside of the viewport are measured, they are drawn in this.\n d.lineMeasure = elt(\"div\", null, \"CodeMirror-measure\");\n // Wraps everything that needs to exist inside the vertically-padded coordinate system\n d.lineSpace = eltP(\"div\", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],\n null, \"position: relative; outline: none\");\n var lines = eltP(\"div\", [d.lineSpace], \"CodeMirror-lines\");\n // Moved around its parent to cover visible view.\n d.mover = elt(\"div\", [lines], null, \"position: relative\");\n // Set to the height of the document, allowing scrolling.\n d.sizer = elt(\"div\", [d.mover], \"CodeMirror-sizer\");\n d.sizerWidth = null;\n // Behavior of elts with overflow: auto and padding is\n // inconsistent across browsers. This is used to ensure the\n // scrollable area is big enough.\n d.heightForcer = elt(\"div\", null, null, \"position: absolute; height: \" + scrollerGap + \"px; width: 1px;\");\n // Will contain the gutters, if any.\n d.gutters = elt(\"div\", null, \"CodeMirror-gutters\");\n d.lineGutter = null;\n // Actual scrollable element.\n d.scroller = elt(\"div\", [d.sizer, d.heightForcer, d.gutters], \"CodeMirror-scroll\");\n d.scroller.setAttribute(\"tabIndex\", \"-1\");\n // The element in which the editor lives.\n d.wrapper = elt(\"div\", [d.scrollbarFiller, d.gutterFiller, d.scroller], \"CodeMirror\");\n // See #6982. FIXME remove when this has been fixed for a while in Chrome\n if (chrome && chrome_version >= 105) { d.wrapper.style.clipPath = \"inset(0px)\"; }\n\n // This attribute is respected by automatic translation systems such as Google Translate,\n // and may also be respected by tools used by human translators.\n d.wrapper.setAttribute('translate', 'no');\n\n // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)\n if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }\n if (!webkit && !(gecko && mobile)) { d.scroller.draggable = true; }\n\n if (place) {\n if (place.appendChild) { place.appendChild(d.wrapper); }\n else { place(d.wrapper); }\n }\n\n // Current rendered range (may be bigger than the view window).\n d.viewFrom = d.viewTo = doc.first;\n d.reportedViewFrom = d.reportedViewTo = doc.first;\n // Information about the rendered lines.\n d.view = [];\n d.renderedView = null;\n // Holds info about a single rendered line when it was rendered\n // for measurement, while not in view.\n d.externalMeasured = null;\n // Empty space (in pixels) above the view\n d.viewOffset = 0;\n d.lastWrapHeight = d.lastWrapWidth = 0;\n d.updateLineNumbers = null;\n\n d.nativeBarWidth = d.barHeight = d.barWidth = 0;\n d.scrollbarsClipped = false;\n\n // Used to only resize the line number gutter when necessary (when\n // the amount of lines crosses a boundary that makes its width change)\n d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;\n // Set to true when a non-horizontal-scrolling line widget is\n // added. As an optimization, line widget aligning is skipped when\n // this is false.\n d.alignWidgets = false;\n\n d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;\n\n // Tracks the maximum line length so that the horizontal scrollbar\n // can be kept static when scrolling.\n d.maxLine = null;\n d.maxLineLength = 0;\n d.maxLineChanged = false;\n\n // Used for measuring wheel scrolling granularity\n d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;\n\n // True when shift is held down.\n d.shift = false;\n\n // Used to track whether anything happened since the context menu\n // was opened.\n d.selForContextMenu = null;\n\n d.activeTouch = null;\n\n d.gutterSpecs = getGutters(options.gutters, options.lineNumbers);\n renderGutters(d);\n\n input.init(d);\n }\n\n // Since the delta values reported on mouse wheel events are\n // unstandardized between browsers and even browser versions, and\n // generally horribly unpredictable, this code starts by measuring\n // the scroll effect that the first few mouse wheel events have,\n // and, from that, detects the way it can convert deltas to pixel\n // offsets afterwards.\n //\n // The reason we want to know the amount a wheel event will scroll\n // is that it gives us a chance to update the display before the\n // actual scrolling happens, reducing flickering.\n\n var wheelSamples = 0, wheelPixelsPerUnit = null;\n // Fill in a browser-detected starting value on browsers where we\n // know one. These don't have to be accurate -- the result of them\n // being wrong would just be a slight flicker on the first wheel\n // scroll (if it is large enough).\n if (ie) { wheelPixelsPerUnit = -.53; }\n else if (gecko) { wheelPixelsPerUnit = 15; }\n else if (chrome) { wheelPixelsPerUnit = -.7; }\n else if (safari) { wheelPixelsPerUnit = -1/3; }\n\n function wheelEventDelta(e) {\n var dx = e.wheelDeltaX, dy = e.wheelDeltaY;\n if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) { dx = e.detail; }\n if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) { dy = e.detail; }\n else if (dy == null) { dy = e.wheelDelta; }\n return {x: dx, y: dy}\n }\n function wheelEventPixels(e) {\n var delta = wheelEventDelta(e);\n delta.x *= wheelPixelsPerUnit;\n delta.y *= wheelPixelsPerUnit;\n return delta\n }\n\n function onScrollWheel(cm, e) {\n // On Chrome 102, viewport updates somehow stop wheel-based\n // scrolling. Turning off pointer events during the scroll seems\n // to avoid the issue.\n if (chrome && chrome_version == 102) {\n if (cm.display.chromeScrollHack == null) { cm.display.sizer.style.pointerEvents = \"none\"; }\n else { clearTimeout(cm.display.chromeScrollHack); }\n cm.display.chromeScrollHack = setTimeout(function () {\n cm.display.chromeScrollHack = null;\n cm.display.sizer.style.pointerEvents = \"\";\n }, 100);\n }\n var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y;\n var pixelsPerUnit = wheelPixelsPerUnit;\n if (e.deltaMode === 0) {\n dx = e.deltaX;\n dy = e.deltaY;\n pixelsPerUnit = 1;\n }\n\n var display = cm.display, scroll = display.scroller;\n // Quit if there's nothing to scroll here\n var canScrollX = scroll.scrollWidth > scroll.clientWidth;\n var canScrollY = scroll.scrollHeight > scroll.clientHeight;\n if (!(dx && canScrollX || dy && canScrollY)) { return }\n\n // Webkit browsers on OS X abort momentum scrolls when the target\n // of the scroll event is removed from the scrollable element.\n // This hack (see related code in patchDisplay) makes sure the\n // element is kept around.\n if (dy && mac && webkit) {\n outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {\n for (var i = 0; i < view.length; i++) {\n if (view[i].node == cur) {\n cm.display.currentWheelTarget = cur;\n break outer\n }\n }\n }\n }\n\n // On some browsers, horizontal scrolling will cause redraws to\n // happen before the gutter has been realigned, causing it to\n // wriggle around in a most unseemly way. When we have an\n // estimated pixels/delta value, we just handle horizontal\n // scrolling entirely here. It'll be slightly off from native, but\n // better than glitching out.\n if (dx && !gecko && !presto && pixelsPerUnit != null) {\n if (dy && canScrollY)\n { updateScrollTop(cm, Math.max(0, scroll.scrollTop + dy * pixelsPerUnit)); }\n setScrollLeft(cm, Math.max(0, scroll.scrollLeft + dx * pixelsPerUnit));\n // Only prevent default scrolling if vertical scrolling is\n // actually possible. Otherwise, it causes vertical scroll\n // jitter on OSX trackpads when deltaX is small and deltaY\n // is large (issue #3579)\n if (!dy || (dy && canScrollY))\n { e_preventDefault(e); }\n display.wheelStartX = null; // Abort measurement, if in progress\n return\n }\n\n // 'Project' the visible viewport to cover the area that is being\n // scrolled into view (if we know enough to estimate it).\n if (dy && pixelsPerUnit != null) {\n var pixels = dy * pixelsPerUnit;\n var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;\n if (pixels < 0) { top = Math.max(0, top + pixels - 50); }\n else { bot = Math.min(cm.doc.height, bot + pixels + 50); }\n updateDisplaySimple(cm, {top: top, bottom: bot});\n }\n\n if (wheelSamples < 20 && e.deltaMode !== 0) {\n if (display.wheelStartX == null) {\n display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;\n display.wheelDX = dx; display.wheelDY = dy;\n setTimeout(function () {\n if (display.wheelStartX == null) { return }\n var movedX = scroll.scrollLeft - display.wheelStartX;\n var movedY = scroll.scrollTop - display.wheelStartY;\n var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||\n (movedX && display.wheelDX && movedX / display.wheelDX);\n display.wheelStartX = display.wheelStartY = null;\n if (!sample) { return }\n wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);\n ++wheelSamples;\n }, 200);\n } else {\n display.wheelDX += dx; display.wheelDY += dy;\n }\n }\n }\n\n // Selection objects are immutable. A new one is created every time\n // the selection changes. A selection is one or more non-overlapping\n // (and non-touching) ranges, sorted, and an integer that indicates\n // which one is the primary selection (the one that's scrolled into\n // view, that getCursor returns, etc).\n var Selection = function(ranges, primIndex) {\n this.ranges = ranges;\n this.primIndex = primIndex;\n };\n\n Selection.prototype.primary = function () { return this.ranges[this.primIndex] };\n\n Selection.prototype.equals = function (other) {\n if (other == this) { return true }\n if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) { return false }\n for (var i = 0; i < this.ranges.length; i++) {\n var here = this.ranges[i], there = other.ranges[i];\n if (!equalCursorPos(here.anchor, there.anchor) || !equalCursorPos(here.head, there.head)) { return false }\n }\n return true\n };\n\n Selection.prototype.deepCopy = function () {\n var out = [];\n for (var i = 0; i < this.ranges.length; i++)\n { out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head)); }\n return new Selection(out, this.primIndex)\n };\n\n Selection.prototype.somethingSelected = function () {\n for (var i = 0; i < this.ranges.length; i++)\n { if (!this.ranges[i].empty()) { return true } }\n return false\n };\n\n Selection.prototype.contains = function (pos, end) {\n if (!end) { end = pos; }\n for (var i = 0; i < this.ranges.length; i++) {\n var range = this.ranges[i];\n if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)\n { return i }\n }\n return -1\n };\n\n var Range = function(anchor, head) {\n this.anchor = anchor; this.head = head;\n };\n\n Range.prototype.from = function () { return minPos(this.anchor, this.head) };\n Range.prototype.to = function () { return maxPos(this.anchor, this.head) };\n Range.prototype.empty = function () { return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch };\n\n // Take an unsorted, potentially overlapping set of ranges, and\n // build a selection out of it. 'Consumes' ranges array (modifying\n // it).\n function normalizeSelection(cm, ranges, primIndex) {\n var mayTouch = cm && cm.options.selectionsMayTouch;\n var prim = ranges[primIndex];\n ranges.sort(function (a, b) { return cmp(a.from(), b.from()); });\n primIndex = indexOf(ranges, prim);\n for (var i = 1; i < ranges.length; i++) {\n var cur = ranges[i], prev = ranges[i - 1];\n var diff = cmp(prev.to(), cur.from());\n if (mayTouch && !cur.empty() ? diff > 0 : diff >= 0) {\n var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());\n var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;\n if (i <= primIndex) { --primIndex; }\n ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));\n }\n }\n return new Selection(ranges, primIndex)\n }\n\n function simpleSelection(anchor, head) {\n return new Selection([new Range(anchor, head || anchor)], 0)\n }\n\n // Compute the position of the end of a change (its 'to' property\n // refers to the pre-change end).\n function changeEnd(change) {\n if (!change.text) { return change.to }\n return Pos(change.from.line + change.text.length - 1,\n lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0))\n }\n\n // Adjust a position to refer to the post-change position of the\n // same text, or the end of the change if the change covers it.\n function adjustForChange(pos, change) {\n if (cmp(pos, change.from) < 0) { return pos }\n if (cmp(pos, change.to) <= 0) { return changeEnd(change) }\n\n var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;\n if (pos.line == change.to.line) { ch += changeEnd(change).ch - change.to.ch; }\n return Pos(line, ch)\n }\n\n function computeSelAfterChange(doc, change) {\n var out = [];\n for (var i = 0; i < doc.sel.ranges.length; i++) {\n var range = doc.sel.ranges[i];\n out.push(new Range(adjustForChange(range.anchor, change),\n adjustForChange(range.head, change)));\n }\n return normalizeSelection(doc.cm, out, doc.sel.primIndex)\n }\n\n function offsetPos(pos, old, nw) {\n if (pos.line == old.line)\n { return Pos(nw.line, pos.ch - old.ch + nw.ch) }\n else\n { return Pos(nw.line + (pos.line - old.line), pos.ch) }\n }\n\n // Used by replaceSelections to allow moving the selection to the\n // start or around the replaced test. Hint may be \"start\" or \"around\".\n function computeReplacedSel(doc, changes, hint) {\n var out = [];\n var oldPrev = Pos(doc.first, 0), newPrev = oldPrev;\n for (var i = 0; i < changes.length; i++) {\n var change = changes[i];\n var from = offsetPos(change.from, oldPrev, newPrev);\n var to = offsetPos(changeEnd(change), oldPrev, newPrev);\n oldPrev = change.to;\n newPrev = to;\n if (hint == \"around\") {\n var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0;\n out[i] = new Range(inv ? to : from, inv ? from : to);\n } else {\n out[i] = new Range(from, from);\n }\n }\n return new Selection(out, doc.sel.primIndex)\n }\n\n // Used to get the editor into a consistent state again when options change.\n\n function loadMode(cm) {\n cm.doc.mode = getMode(cm.options, cm.doc.modeOption);\n resetModeState(cm);\n }\n\n function resetModeState(cm) {\n cm.doc.iter(function (line) {\n if (line.stateAfter) { line.stateAfter = null; }\n if (line.styles) { line.styles = null; }\n });\n cm.doc.modeFrontier = cm.doc.highlightFrontier = cm.doc.first;\n startWorker(cm, 100);\n cm.state.modeGen++;\n if (cm.curOp) { regChange(cm); }\n }\n\n // DOCUMENT DATA STRUCTURE\n\n // By default, updates that start and end at the beginning of a line\n // are treated specially, in order to make the association of line\n // widgets and marker elements with the text behave more intuitive.\n function isWholeLineUpdate(doc, change) {\n return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == \"\" &&\n (!doc.cm || doc.cm.options.wholeLineUpdateBefore)\n }\n\n // Perform a change on the document data structure.\n function updateDoc(doc, change, markedSpans, estimateHeight) {\n function spansFor(n) {return markedSpans ? markedSpans[n] : null}\n function update(line, text, spans) {\n updateLine(line, text, spans, estimateHeight);\n signalLater(line, \"change\", line, change);\n }\n function linesFor(start, end) {\n var result = [];\n for (var i = start; i < end; ++i)\n { result.push(new Line(text[i], spansFor(i), estimateHeight)); }\n return result\n }\n\n var from = change.from, to = change.to, text = change.text;\n var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);\n var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;\n\n // Adjust the line structure\n if (change.full) {\n doc.insert(0, linesFor(0, text.length));\n doc.remove(text.length, doc.size - text.length);\n } else if (isWholeLineUpdate(doc, change)) {\n // This is a whole-line replace. Treated specially to make\n // sure line objects move the way they are supposed to.\n var added = linesFor(0, text.length - 1);\n update(lastLine, lastLine.text, lastSpans);\n if (nlines) { doc.remove(from.line, nlines); }\n if (added.length) { doc.insert(from.line, added); }\n } else if (firstLine == lastLine) {\n if (text.length == 1) {\n update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);\n } else {\n var added$1 = linesFor(1, text.length - 1);\n added$1.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight));\n update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));\n doc.insert(from.line + 1, added$1);\n }\n } else if (text.length == 1) {\n update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));\n doc.remove(from.line + 1, nlines);\n } else {\n update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));\n update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);\n var added$2 = linesFor(1, text.length - 1);\n if (nlines > 1) { doc.remove(from.line + 1, nlines - 1); }\n doc.insert(from.line + 1, added$2);\n }\n\n signalLater(doc, \"change\", doc, change);\n }\n\n // Call f for all linked documents.\n function linkedDocs(doc, f, sharedHistOnly) {\n function propagate(doc, skip, sharedHist) {\n if (doc.linked) { for (var i = 0; i < doc.linked.length; ++i) {\n var rel = doc.linked[i];\n if (rel.doc == skip) { continue }\n var shared = sharedHist && rel.sharedHist;\n if (sharedHistOnly && !shared) { continue }\n f(rel.doc, shared);\n propagate(rel.doc, doc, shared);\n } }\n }\n propagate(doc, null, true);\n }\n\n // Attach a document to an editor.\n function attachDoc(cm, doc) {\n if (doc.cm) { throw new Error(\"This document is already in use.\") }\n cm.doc = doc;\n doc.cm = cm;\n estimateLineHeights(cm);\n loadMode(cm);\n setDirectionClass(cm);\n cm.options.direction = doc.direction;\n if (!cm.options.lineWrapping) { findMaxLine(cm); }\n cm.options.mode = doc.modeOption;\n regChange(cm);\n }\n\n function setDirectionClass(cm) {\n (cm.doc.direction == \"rtl\" ? addClass : rmClass)(cm.display.lineDiv, \"CodeMirror-rtl\");\n }\n\n function directionChanged(cm) {\n runInOp(cm, function () {\n setDirectionClass(cm);\n regChange(cm);\n });\n }\n\n function History(prev) {\n // Arrays of change events and selections. Doing something adds an\n // event to done and clears undo. Undoing moves events from done\n // to undone, redoing moves them in the other direction.\n this.done = []; this.undone = [];\n this.undoDepth = prev ? prev.undoDepth : Infinity;\n // Used to track when changes can be merged into a single undo\n // event\n this.lastModTime = this.lastSelTime = 0;\n this.lastOp = this.lastSelOp = null;\n this.lastOrigin = this.lastSelOrigin = null;\n // Used by the isClean() method\n this.generation = this.maxGeneration = prev ? prev.maxGeneration : 1;\n }\n\n // Create a history change event from an updateDoc-style change\n // object.\n function historyChangeFromChange(doc, change) {\n var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)};\n attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);\n linkedDocs(doc, function (doc) { return attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); }, true);\n return histChange\n }\n\n // Pop all selection events off the end of a history array. Stop at\n // a change event.\n function clearSelectionEvents(array) {\n while (array.length) {\n var last = lst(array);\n if (last.ranges) { array.pop(); }\n else { break }\n }\n }\n\n // Find the top change event in the history. Pop off selection\n // events that are in the way.\n function lastChangeEvent(hist, force) {\n if (force) {\n clearSelectionEvents(hist.done);\n return lst(hist.done)\n } else if (hist.done.length && !lst(hist.done).ranges) {\n return lst(hist.done)\n } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {\n hist.done.pop();\n return lst(hist.done)\n }\n }\n\n // Register a change in the history. Merges changes that are within\n // a single operation, or are close together with an origin that\n // allows merging (starting with \"+\") into a single event.\n function addChangeToHistory(doc, change, selAfter, opId) {\n var hist = doc.history;\n hist.undone.length = 0;\n var time = +new Date, cur;\n var last;\n\n if ((hist.lastOp == opId ||\n hist.lastOrigin == change.origin && change.origin &&\n ((change.origin.charAt(0) == \"+\" && hist.lastModTime > time - (doc.cm ? doc.cm.options.historyEventDelay : 500)) ||\n change.origin.charAt(0) == \"*\")) &&\n (cur = lastChangeEvent(hist, hist.lastOp == opId))) {\n // Merge this change into the last event\n last = lst(cur.changes);\n if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {\n // Optimized case for simple insertion -- don't want to add\n // new changesets for every character typed\n last.to = changeEnd(change);\n } else {\n // Add new sub-event\n cur.changes.push(historyChangeFromChange(doc, change));\n }\n } else {\n // Can not be merged, start a new event.\n var before = lst(hist.done);\n if (!before || !before.ranges)\n { pushSelectionToHistory(doc.sel, hist.done); }\n cur = {changes: [historyChangeFromChange(doc, change)],\n generation: hist.generation};\n hist.done.push(cur);\n while (hist.done.length > hist.undoDepth) {\n hist.done.shift();\n if (!hist.done[0].ranges) { hist.done.shift(); }\n }\n }\n hist.done.push(selAfter);\n hist.generation = ++hist.maxGeneration;\n hist.lastModTime = hist.lastSelTime = time;\n hist.lastOp = hist.lastSelOp = opId;\n hist.lastOrigin = hist.lastSelOrigin = change.origin;\n\n if (!last) { signal(doc, \"historyAdded\"); }\n }\n\n function selectionEventCanBeMerged(doc, origin, prev, sel) {\n var ch = origin.charAt(0);\n return ch == \"*\" ||\n ch == \"+\" &&\n prev.ranges.length == sel.ranges.length &&\n prev.somethingSelected() == sel.somethingSelected() &&\n new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500)\n }\n\n // Called whenever the selection changes, sets the new selection as\n // the pending selection in the history, and pushes the old pending\n // selection into the 'done' array when it was significantly\n // different (in number of selected ranges, emptiness, or time).\n function addSelectionToHistory(doc, sel, opId, options) {\n var hist = doc.history, origin = options && options.origin;\n\n // A new event is started when the previous origin does not match\n // the current, or the origins don't allow matching. Origins\n // starting with * are always merged, those starting with + are\n // merged when similar and close together in time.\n if (opId == hist.lastSelOp ||\n (origin && hist.lastSelOrigin == origin &&\n (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||\n selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))\n { hist.done[hist.done.length - 1] = sel; }\n else\n { pushSelectionToHistory(sel, hist.done); }\n\n hist.lastSelTime = +new Date;\n hist.lastSelOrigin = origin;\n hist.lastSelOp = opId;\n if (options && options.clearRedo !== false)\n { clearSelectionEvents(hist.undone); }\n }\n\n function pushSelectionToHistory(sel, dest) {\n var top = lst(dest);\n if (!(top && top.ranges && top.equals(sel)))\n { dest.push(sel); }\n }\n\n // Used to store marked span information in the history.\n function attachLocalSpans(doc, change, from, to) {\n var existing = change[\"spans_\" + doc.id], n = 0;\n doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) {\n if (line.markedSpans)\n { (existing || (existing = change[\"spans_\" + doc.id] = {}))[n] = line.markedSpans; }\n ++n;\n });\n }\n\n // When un/re-doing restores text containing marked spans, those\n // that have been explicitly cleared should not be restored.\n function removeClearedSpans(spans) {\n if (!spans) { return null }\n var out;\n for (var i = 0; i < spans.length; ++i) {\n if (spans[i].marker.explicitlyCleared) { if (!out) { out = spans.slice(0, i); } }\n else if (out) { out.push(spans[i]); }\n }\n return !out ? spans : out.length ? out : null\n }\n\n // Retrieve and filter the old marked spans stored in a change event.\n function getOldSpans(doc, change) {\n var found = change[\"spans_\" + doc.id];\n if (!found) { return null }\n var nw = [];\n for (var i = 0; i < change.text.length; ++i)\n { nw.push(removeClearedSpans(found[i])); }\n return nw\n }\n\n // Used for un/re-doing changes from the history. Combines the\n // result of computing the existing spans with the set of spans that\n // existed in the history (so that deleting around a span and then\n // undoing brings back the span).\n function mergeOldSpans(doc, change) {\n var old = getOldSpans(doc, change);\n var stretched = stretchSpansOverChange(doc, change);\n if (!old) { return stretched }\n if (!stretched) { return old }\n\n for (var i = 0; i < old.length; ++i) {\n var oldCur = old[i], stretchCur = stretched[i];\n if (oldCur && stretchCur) {\n spans: for (var j = 0; j < stretchCur.length; ++j) {\n var span = stretchCur[j];\n for (var k = 0; k < oldCur.length; ++k)\n { if (oldCur[k].marker == span.marker) { continue spans } }\n oldCur.push(span);\n }\n } else if (stretchCur) {\n old[i] = stretchCur;\n }\n }\n return old\n }\n\n // Used both to provide a JSON-safe object in .getHistory, and, when\n // detaching a document, to split the history in two\n function copyHistoryArray(events, newGroup, instantiateSel) {\n var copy = [];\n for (var i = 0; i < events.length; ++i) {\n var event = events[i];\n if (event.ranges) {\n copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event);\n continue\n }\n var changes = event.changes, newChanges = [];\n copy.push({changes: newChanges});\n for (var j = 0; j < changes.length; ++j) {\n var change = changes[j], m = (void 0);\n newChanges.push({from: change.from, to: change.to, text: change.text});\n if (newGroup) { for (var prop in change) { if (m = prop.match(/^spans_(\\d+)$/)) {\n if (indexOf(newGroup, Number(m[1])) > -1) {\n lst(newChanges)[prop] = change[prop];\n delete change[prop];\n }\n } } }\n }\n }\n return copy\n }\n\n // The 'scroll' parameter given to many of these indicated whether\n // the new cursor position should be scrolled into view after\n // modifying the selection.\n\n // If shift is held or the extend flag is set, extends a range to\n // include a given position (and optionally a second position).\n // Otherwise, simply returns the range between the given positions.\n // Used for cursor motion and such.\n function extendRange(range, head, other, extend) {\n if (extend) {\n var anchor = range.anchor;\n if (other) {\n var posBefore = cmp(head, anchor) < 0;\n if (posBefore != (cmp(other, anchor) < 0)) {\n anchor = head;\n head = other;\n } else if (posBefore != (cmp(head, other) < 0)) {\n head = other;\n }\n }\n return new Range(anchor, head)\n } else {\n return new Range(other || head, head)\n }\n }\n\n // Extend the primary selection range, discard the rest.\n function extendSelection(doc, head, other, options, extend) {\n if (extend == null) { extend = doc.cm && (doc.cm.display.shift || doc.extend); }\n setSelection(doc, new Selection([extendRange(doc.sel.primary(), head, other, extend)], 0), options);\n }\n\n // Extend all selections (pos is an array of selections with length\n // equal the number of selections)\n function extendSelections(doc, heads, options) {\n var out = [];\n var extend = doc.cm && (doc.cm.display.shift || doc.extend);\n for (var i = 0; i < doc.sel.ranges.length; i++)\n { out[i] = extendRange(doc.sel.ranges[i], heads[i], null, extend); }\n var newSel = normalizeSelection(doc.cm, out, doc.sel.primIndex);\n setSelection(doc, newSel, options);\n }\n\n // Updates a single range in the selection.\n function replaceOneSelection(doc, i, range, options) {\n var ranges = doc.sel.ranges.slice(0);\n ranges[i] = range;\n setSelection(doc, normalizeSelection(doc.cm, ranges, doc.sel.primIndex), options);\n }\n\n // Reset the selection to a single range.\n function setSimpleSelection(doc, anchor, head, options) {\n setSelection(doc, simpleSelection(anchor, head), options);\n }\n\n // Give beforeSelectionChange handlers a change to influence a\n // selection update.\n function filterSelectionChange(doc, sel, options) {\n var obj = {\n ranges: sel.ranges,\n update: function(ranges) {\n this.ranges = [];\n for (var i = 0; i < ranges.length; i++)\n { this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),\n clipPos(doc, ranges[i].head)); }\n },\n origin: options && options.origin\n };\n signal(doc, \"beforeSelectionChange\", doc, obj);\n if (doc.cm) { signal(doc.cm, \"beforeSelectionChange\", doc.cm, obj); }\n if (obj.ranges != sel.ranges) { return normalizeSelection(doc.cm, obj.ranges, obj.ranges.length - 1) }\n else { return sel }\n }\n\n function setSelectionReplaceHistory(doc, sel, options) {\n var done = doc.history.done, last = lst(done);\n if (last && last.ranges) {\n done[done.length - 1] = sel;\n setSelectionNoUndo(doc, sel, options);\n } else {\n setSelection(doc, sel, options);\n }\n }\n\n // Set a new selection.\n function setSelection(doc, sel, options) {\n setSelectionNoUndo(doc, sel, options);\n addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options);\n }\n\n function setSelectionNoUndo(doc, sel, options) {\n if (hasHandler(doc, \"beforeSelectionChange\") || doc.cm && hasHandler(doc.cm, \"beforeSelectionChange\"))\n { sel = filterSelectionChange(doc, sel, options); }\n\n var bias = options && options.bias ||\n (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1);\n setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));\n\n if (!(options && options.scroll === false) && doc.cm && doc.cm.getOption(\"readOnly\") != \"nocursor\")\n { ensureCursorVisible(doc.cm); }\n }\n\n function setSelectionInner(doc, sel) {\n if (sel.equals(doc.sel)) { return }\n\n doc.sel = sel;\n\n if (doc.cm) {\n doc.cm.curOp.updateInput = 1;\n doc.cm.curOp.selectionChanged = true;\n signalCursorActivity(doc.cm);\n }\n signalLater(doc, \"cursorActivity\", doc);\n }\n\n // Verify that the selection does not partially select any atomic\n // marked ranges.\n function reCheckSelection(doc) {\n setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false));\n }\n\n // Return a selection that does not partially select any atomic\n // ranges.\n function skipAtomicInSelection(doc, sel, bias, mayClear) {\n var out;\n for (var i = 0; i < sel.ranges.length; i++) {\n var range = sel.ranges[i];\n var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i];\n var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear);\n var newHead = range.head == range.anchor ? newAnchor : skipAtomic(doc, range.head, old && old.head, bias, mayClear);\n if (out || newAnchor != range.anchor || newHead != range.head) {\n if (!out) { out = sel.ranges.slice(0, i); }\n out[i] = new Range(newAnchor, newHead);\n }\n }\n return out ? normalizeSelection(doc.cm, out, sel.primIndex) : sel\n }\n\n function skipAtomicInner(doc, pos, oldPos, dir, mayClear) {\n var line = getLine(doc, pos.line);\n if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {\n var sp = line.markedSpans[i], m = sp.marker;\n\n // Determine if we should prevent the cursor being placed to the left/right of an atomic marker\n // Historically this was determined using the inclusiveLeft/Right option, but the new way to control it\n // is with selectLeft/Right\n var preventCursorLeft = (\"selectLeft\" in m) ? !m.selectLeft : m.inclusiveLeft;\n var preventCursorRight = (\"selectRight\" in m) ? !m.selectRight : m.inclusiveRight;\n\n if ((sp.from == null || (preventCursorLeft ? sp.from <= pos.ch : sp.from < pos.ch)) &&\n (sp.to == null || (preventCursorRight ? sp.to >= pos.ch : sp.to > pos.ch))) {\n if (mayClear) {\n signal(m, \"beforeCursorEnter\");\n if (m.explicitlyCleared) {\n if (!line.markedSpans) { break }\n else {--i; continue}\n }\n }\n if (!m.atomic) { continue }\n\n if (oldPos) {\n var near = m.find(dir < 0 ? 1 : -1), diff = (void 0);\n if (dir < 0 ? preventCursorRight : preventCursorLeft)\n { near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null); }\n if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0))\n { return skipAtomicInner(doc, near, pos, dir, mayClear) }\n }\n\n var far = m.find(dir < 0 ? -1 : 1);\n if (dir < 0 ? preventCursorLeft : preventCursorRight)\n { far = movePos(doc, far, dir, far.line == pos.line ? line : null); }\n return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null\n }\n } }\n return pos\n }\n\n // Ensure a given position is not inside an atomic range.\n function skipAtomic(doc, pos, oldPos, bias, mayClear) {\n var dir = bias || 1;\n var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) ||\n (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) ||\n skipAtomicInner(doc, pos, oldPos, -dir, mayClear) ||\n (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true));\n if (!found) {\n doc.cantEdit = true;\n return Pos(doc.first, 0)\n }\n return found\n }\n\n function movePos(doc, pos, dir, line) {\n if (dir < 0 && pos.ch == 0) {\n if (pos.line > doc.first) { return clipPos(doc, Pos(pos.line - 1)) }\n else { return null }\n } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) {\n if (pos.line < doc.first + doc.size - 1) { return Pos(pos.line + 1, 0) }\n else { return null }\n } else {\n return new Pos(pos.line, pos.ch + dir)\n }\n }\n\n function selectAll(cm) {\n cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);\n }\n\n // UPDATING\n\n // Allow \"beforeChange\" event handlers to influence a change\n function filterChange(doc, change, update) {\n var obj = {\n canceled: false,\n from: change.from,\n to: change.to,\n text: change.text,\n origin: change.origin,\n cancel: function () { return obj.canceled = true; }\n };\n if (update) { obj.update = function (from, to, text, origin) {\n if (from) { obj.from = clipPos(doc, from); }\n if (to) { obj.to = clipPos(doc, to); }\n if (text) { obj.text = text; }\n if (origin !== undefined) { obj.origin = origin; }\n }; }\n signal(doc, \"beforeChange\", doc, obj);\n if (doc.cm) { signal(doc.cm, \"beforeChange\", doc.cm, obj); }\n\n if (obj.canceled) {\n if (doc.cm) { doc.cm.curOp.updateInput = 2; }\n return null\n }\n return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin}\n }\n\n // Apply a change to a document, and add it to the document's\n // history, and propagating it to all linked documents.\n function makeChange(doc, change, ignoreReadOnly) {\n if (doc.cm) {\n if (!doc.cm.curOp) { return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly) }\n if (doc.cm.state.suppressEdits) { return }\n }\n\n if (hasHandler(doc, \"beforeChange\") || doc.cm && hasHandler(doc.cm, \"beforeChange\")) {\n change = filterChange(doc, change, true);\n if (!change) { return }\n }\n\n // Possibly split or suppress the update based on the presence\n // of read-only spans in its range.\n var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);\n if (split) {\n for (var i = split.length - 1; i >= 0; --i)\n { makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [\"\"] : change.text, origin: change.origin}); }\n } else {\n makeChangeInner(doc, change);\n }\n }\n\n function makeChangeInner(doc, change) {\n if (change.text.length == 1 && change.text[0] == \"\" && cmp(change.from, change.to) == 0) { return }\n var selAfter = computeSelAfterChange(doc, change);\n addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);\n\n makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));\n var rebased = [];\n\n linkedDocs(doc, function (doc, sharedHist) {\n if (!sharedHist && indexOf(rebased, doc.history) == -1) {\n rebaseHist(doc.history, change);\n rebased.push(doc.history);\n }\n makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));\n });\n }\n\n // Revert a change stored in a document's history.\n function makeChangeFromHistory(doc, type, allowSelectionOnly) {\n var suppress = doc.cm && doc.cm.state.suppressEdits;\n if (suppress && !allowSelectionOnly) { return }\n\n var hist = doc.history, event, selAfter = doc.sel;\n var source = type == \"undo\" ? hist.done : hist.undone, dest = type == \"undo\" ? hist.undone : hist.done;\n\n // Verify that there is a useable event (so that ctrl-z won't\n // needlessly clear selection events)\n var i = 0;\n for (; i < source.length; i++) {\n event = source[i];\n if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)\n { break }\n }\n if (i == source.length) { return }\n hist.lastOrigin = hist.lastSelOrigin = null;\n\n for (;;) {\n event = source.pop();\n if (event.ranges) {\n pushSelectionToHistory(event, dest);\n if (allowSelectionOnly && !event.equals(doc.sel)) {\n setSelection(doc, event, {clearRedo: false});\n return\n }\n selAfter = event;\n } else if (suppress) {\n source.push(event);\n return\n } else { break }\n }\n\n // Build up a reverse change object to add to the opposite history\n // stack (redo when undoing, and vice versa).\n var antiChanges = [];\n pushSelectionToHistory(selAfter, dest);\n dest.push({changes: antiChanges, generation: hist.generation});\n hist.generation = event.generation || ++hist.maxGeneration;\n\n var filter = hasHandler(doc, \"beforeChange\") || doc.cm && hasHandler(doc.cm, \"beforeChange\");\n\n var loop = function ( i ) {\n var change = event.changes[i];\n change.origin = type;\n if (filter && !filterChange(doc, change, false)) {\n source.length = 0;\n return {}\n }\n\n antiChanges.push(historyChangeFromChange(doc, change));\n\n var after = i ? computeSelAfterChange(doc, change) : lst(source);\n makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));\n if (!i && doc.cm) { doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}); }\n var rebased = [];\n\n // Propagate to the linked documents\n linkedDocs(doc, function (doc, sharedHist) {\n if (!sharedHist && indexOf(rebased, doc.history) == -1) {\n rebaseHist(doc.history, change);\n rebased.push(doc.history);\n }\n makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));\n });\n };\n\n for (var i$1 = event.changes.length - 1; i$1 >= 0; --i$1) {\n var returned = loop( i$1 );\n\n if ( returned ) return returned.v;\n }\n }\n\n // Sub-views need their line numbers shifted when text is added\n // above or below them in the parent document.\n function shiftDoc(doc, distance) {\n if (distance == 0) { return }\n doc.first += distance;\n doc.sel = new Selection(map(doc.sel.ranges, function (range) { return new Range(\n Pos(range.anchor.line + distance, range.anchor.ch),\n Pos(range.head.line + distance, range.head.ch)\n ); }), doc.sel.primIndex);\n if (doc.cm) {\n regChange(doc.cm, doc.first, doc.first - distance, distance);\n for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)\n { regLineChange(doc.cm, l, \"gutter\"); }\n }\n }\n\n // More lower-level change function, handling only a single document\n // (not linked ones).\n function makeChangeSingleDoc(doc, change, selAfter, spans) {\n if (doc.cm && !doc.cm.curOp)\n { return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans) }\n\n if (change.to.line < doc.first) {\n shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));\n return\n }\n if (change.from.line > doc.lastLine()) { return }\n\n // Clip the change to the size of this doc\n if (change.from.line < doc.first) {\n var shift = change.text.length - 1 - (doc.first - change.from.line);\n shiftDoc(doc, shift);\n change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),\n text: [lst(change.text)], origin: change.origin};\n }\n var last = doc.lastLine();\n if (change.to.line > last) {\n change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),\n text: [change.text[0]], origin: change.origin};\n }\n\n change.removed = getBetween(doc, change.from, change.to);\n\n if (!selAfter) { selAfter = computeSelAfterChange(doc, change); }\n if (doc.cm) { makeChangeSingleDocInEditor(doc.cm, change, spans); }\n else { updateDoc(doc, change, spans); }\n setSelectionNoUndo(doc, selAfter, sel_dontScroll);\n\n if (doc.cantEdit && skipAtomic(doc, Pos(doc.firstLine(), 0)))\n { doc.cantEdit = false; }\n }\n\n // Handle the interaction of a change to a document with the editor\n // that this document is part of.\n function makeChangeSingleDocInEditor(cm, change, spans) {\n var doc = cm.doc, display = cm.display, from = change.from, to = change.to;\n\n var recomputeMaxLength = false, checkWidthStart = from.line;\n if (!cm.options.lineWrapping) {\n checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));\n doc.iter(checkWidthStart, to.line + 1, function (line) {\n if (line == display.maxLine) {\n recomputeMaxLength = true;\n return true\n }\n });\n }\n\n if (doc.sel.contains(change.from, change.to) > -1)\n { signalCursorActivity(cm); }\n\n updateDoc(doc, change, spans, estimateHeight(cm));\n\n if (!cm.options.lineWrapping) {\n doc.iter(checkWidthStart, from.line + change.text.length, function (line) {\n var len = lineLength(line);\n if (len > display.maxLineLength) {\n display.maxLine = line;\n display.maxLineLength = len;\n display.maxLineChanged = true;\n recomputeMaxLength = false;\n }\n });\n if (recomputeMaxLength) { cm.curOp.updateMaxLine = true; }\n }\n\n retreatFrontier(doc, from.line);\n startWorker(cm, 400);\n\n var lendiff = change.text.length - (to.line - from.line) - 1;\n // Remember that these lines changed, for updating the display\n if (change.full)\n { regChange(cm); }\n else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))\n { regLineChange(cm, from.line, \"text\"); }\n else\n { regChange(cm, from.line, to.line + 1, lendiff); }\n\n var changesHandler = hasHandler(cm, \"changes\"), changeHandler = hasHandler(cm, \"change\");\n if (changeHandler || changesHandler) {\n var obj = {\n from: from, to: to,\n text: change.text,\n removed: change.removed,\n origin: change.origin\n };\n if (changeHandler) { signalLater(cm, \"change\", cm, obj); }\n if (changesHandler) { (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj); }\n }\n cm.display.selForContextMenu = null;\n }\n\n function replaceRange(doc, code, from, to, origin) {\n var assign;\n\n if (!to) { to = from; }\n if (cmp(to, from) < 0) { (assign = [to, from], from = assign[0], to = assign[1]); }\n if (typeof code == \"string\") { code = doc.splitLines(code); }\n makeChange(doc, {from: from, to: to, text: code, origin: origin});\n }\n\n // Rebasing/resetting history to deal with externally-sourced changes\n\n function rebaseHistSelSingle(pos, from, to, diff) {\n if (to < pos.line) {\n pos.line += diff;\n } else if (from < pos.line) {\n pos.line = from;\n pos.ch = 0;\n }\n }\n\n // Tries to rebase an array of history events given a change in the\n // document. If the change touches the same lines as the event, the\n // event, and everything 'behind' it, is discarded. If the change is\n // before the event, the event's positions are updated. Uses a\n // copy-on-write scheme for the positions, to avoid having to\n // reallocate them all on every rebase, but also avoid problems with\n // shared position objects being unsafely updated.\n function rebaseHistArray(array, from, to, diff) {\n for (var i = 0; i < array.length; ++i) {\n var sub = array[i], ok = true;\n if (sub.ranges) {\n if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; }\n for (var j = 0; j < sub.ranges.length; j++) {\n rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);\n rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);\n }\n continue\n }\n for (var j$1 = 0; j$1 < sub.changes.length; ++j$1) {\n var cur = sub.changes[j$1];\n if (to < cur.from.line) {\n cur.from = Pos(cur.from.line + diff, cur.from.ch);\n cur.to = Pos(cur.to.line + diff, cur.to.ch);\n } else if (from <= cur.to.line) {\n ok = false;\n break\n }\n }\n if (!ok) {\n array.splice(0, i + 1);\n i = 0;\n }\n }\n }\n\n function rebaseHist(hist, change) {\n var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;\n rebaseHistArray(hist.done, from, to, diff);\n rebaseHistArray(hist.undone, from, to, diff);\n }\n\n // Utility for applying a change to a line by handle or number,\n // returning the number and optionally registering the line as\n // changed.\n function changeLine(doc, handle, changeType, op) {\n var no = handle, line = handle;\n if (typeof handle == \"number\") { line = getLine(doc, clipLine(doc, handle)); }\n else { no = lineNo(handle); }\n if (no == null) { return null }\n if (op(line, no) && doc.cm) { regLineChange(doc.cm, no, changeType); }\n return line\n }\n\n // The document is represented as a BTree consisting of leaves, with\n // chunk of lines in them, and branches, with up to ten leaves or\n // other branch nodes below them. The top node is always a branch\n // node, and is the document object itself (meaning it has\n // additional methods and properties).\n //\n // All nodes have parent links. The tree is used both to go from\n // line numbers to line objects, and to go from objects to numbers.\n // It also indexes by height, and is used to convert between height\n // and line object, and to find the total height of the document.\n //\n // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html\n\n function LeafChunk(lines) {\n this.lines = lines;\n this.parent = null;\n var height = 0;\n for (var i = 0; i < lines.length; ++i) {\n lines[i].parent = this;\n height += lines[i].height;\n }\n this.height = height;\n }\n\n LeafChunk.prototype = {\n chunkSize: function() { return this.lines.length },\n\n // Remove the n lines at offset 'at'.\n removeInner: function(at, n) {\n for (var i = at, e = at + n; i < e; ++i) {\n var line = this.lines[i];\n this.height -= line.height;\n cleanUpLine(line);\n signalLater(line, \"delete\");\n }\n this.lines.splice(at, n);\n },\n\n // Helper used to collapse a small branch into a single leaf.\n collapse: function(lines) {\n lines.push.apply(lines, this.lines);\n },\n\n // Insert the given array of lines at offset 'at', count them as\n // having the given height.\n insertInner: function(at, lines, height) {\n this.height += height;\n this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));\n for (var i = 0; i < lines.length; ++i) { lines[i].parent = this; }\n },\n\n // Used to iterate over a part of the tree.\n iterN: function(at, n, op) {\n for (var e = at + n; at < e; ++at)\n { if (op(this.lines[at])) { return true } }\n }\n };\n\n function BranchChunk(children) {\n this.children = children;\n var size = 0, height = 0;\n for (var i = 0; i < children.length; ++i) {\n var ch = children[i];\n size += ch.chunkSize(); height += ch.height;\n ch.parent = this;\n }\n this.size = size;\n this.height = height;\n this.parent = null;\n }\n\n BranchChunk.prototype = {\n chunkSize: function() { return this.size },\n\n removeInner: function(at, n) {\n this.size -= n;\n for (var i = 0; i < this.children.length; ++i) {\n var child = this.children[i], sz = child.chunkSize();\n if (at < sz) {\n var rm = Math.min(n, sz - at), oldHeight = child.height;\n child.removeInner(at, rm);\n this.height -= oldHeight - child.height;\n if (sz == rm) { this.children.splice(i--, 1); child.parent = null; }\n if ((n -= rm) == 0) { break }\n at = 0;\n } else { at -= sz; }\n }\n // If the result is smaller than 25 lines, ensure that it is a\n // single leaf node.\n if (this.size - n < 25 &&\n (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {\n var lines = [];\n this.collapse(lines);\n this.children = [new LeafChunk(lines)];\n this.children[0].parent = this;\n }\n },\n\n collapse: function(lines) {\n for (var i = 0; i < this.children.length; ++i) { this.children[i].collapse(lines); }\n },\n\n insertInner: function(at, lines, height) {\n this.size += lines.length;\n this.height += height;\n for (var i = 0; i < this.children.length; ++i) {\n var child = this.children[i], sz = child.chunkSize();\n if (at <= sz) {\n child.insertInner(at, lines, height);\n if (child.lines && child.lines.length > 50) {\n // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced.\n // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest.\n var remaining = child.lines.length % 25 + 25;\n for (var pos = remaining; pos < child.lines.length;) {\n var leaf = new LeafChunk(child.lines.slice(pos, pos += 25));\n child.height -= leaf.height;\n this.children.splice(++i, 0, leaf);\n leaf.parent = this;\n }\n child.lines = child.lines.slice(0, remaining);\n this.maybeSpill();\n }\n break\n }\n at -= sz;\n }\n },\n\n // When a node has grown, check whether it should be split.\n maybeSpill: function() {\n if (this.children.length <= 10) { return }\n var me = this;\n do {\n var spilled = me.children.splice(me.children.length - 5, 5);\n var sibling = new BranchChunk(spilled);\n if (!me.parent) { // Become the parent node\n var copy = new BranchChunk(me.children);\n copy.parent = me;\n me.children = [copy, sibling];\n me = copy;\n } else {\n me.size -= sibling.size;\n me.height -= sibling.height;\n var myIndex = indexOf(me.parent.children, me);\n me.parent.children.splice(myIndex + 1, 0, sibling);\n }\n sibling.parent = me.parent;\n } while (me.children.length > 10)\n me.parent.maybeSpill();\n },\n\n iterN: function(at, n, op) {\n for (var i = 0; i < this.children.length; ++i) {\n var child = this.children[i], sz = child.chunkSize();\n if (at < sz) {\n var used = Math.min(n, sz - at);\n if (child.iterN(at, used, op)) { return true }\n if ((n -= used) == 0) { break }\n at = 0;\n } else { at -= sz; }\n }\n }\n };\n\n // Line widgets are block elements displayed above or below a line.\n\n var LineWidget = function(doc, node, options) {\n if (options) { for (var opt in options) { if (options.hasOwnProperty(opt))\n { this[opt] = options[opt]; } } }\n this.doc = doc;\n this.node = node;\n };\n\n LineWidget.prototype.clear = function () {\n var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);\n if (no == null || !ws) { return }\n for (var i = 0; i < ws.length; ++i) { if (ws[i] == this) { ws.splice(i--, 1); } }\n if (!ws.length) { line.widgets = null; }\n var height = widgetHeight(this);\n updateLineHeight(line, Math.max(0, line.height - height));\n if (cm) {\n runInOp(cm, function () {\n adjustScrollWhenAboveVisible(cm, line, -height);\n regLineChange(cm, no, \"widget\");\n });\n signalLater(cm, \"lineWidgetCleared\", cm, this, no);\n }\n };\n\n LineWidget.prototype.changed = function () {\n var this$1 = this;\n\n var oldH = this.height, cm = this.doc.cm, line = this.line;\n this.height = null;\n var diff = widgetHeight(this) - oldH;\n if (!diff) { return }\n if (!lineIsHidden(this.doc, line)) { updateLineHeight(line, line.height + diff); }\n if (cm) {\n runInOp(cm, function () {\n cm.curOp.forceUpdate = true;\n adjustScrollWhenAboveVisible(cm, line, diff);\n signalLater(cm, \"lineWidgetChanged\", cm, this$1, lineNo(line));\n });\n }\n };\n eventMixin(LineWidget);\n\n function adjustScrollWhenAboveVisible(cm, line, diff) {\n if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))\n { addToScrollTop(cm, diff); }\n }\n\n function addLineWidget(doc, handle, node, options) {\n var widget = new LineWidget(doc, node, options);\n var cm = doc.cm;\n if (cm && widget.noHScroll) { cm.display.alignWidgets = true; }\n changeLine(doc, handle, \"widget\", function (line) {\n var widgets = line.widgets || (line.widgets = []);\n if (widget.insertAt == null) { widgets.push(widget); }\n else { widgets.splice(Math.min(widgets.length, Math.max(0, widget.insertAt)), 0, widget); }\n widget.line = line;\n if (cm && !lineIsHidden(doc, line)) {\n var aboveVisible = heightAtLine(line) < doc.scrollTop;\n updateLineHeight(line, line.height + widgetHeight(widget));\n if (aboveVisible) { addToScrollTop(cm, widget.height); }\n cm.curOp.forceUpdate = true;\n }\n return true\n });\n if (cm) { signalLater(cm, \"lineWidgetAdded\", cm, widget, typeof handle == \"number\" ? handle : lineNo(handle)); }\n return widget\n }\n\n // TEXTMARKERS\n\n // Created with markText and setBookmark methods. A TextMarker is a\n // handle that can be used to clear or find a marked position in the\n // document. Line objects hold arrays (markedSpans) containing\n // {from, to, marker} object pointing to such marker objects, and\n // indicating that such a marker is present on that line. Multiple\n // lines may point to the same marker when it spans across lines.\n // The spans will have null for their from/to properties when the\n // marker continues beyond the start/end of the line. Markers have\n // links back to the lines they currently touch.\n\n // Collapsed markers have unique ids, in order to be able to order\n // them, which is needed for uniquely determining an outer marker\n // when they overlap (they may nest, but not partially overlap).\n var nextMarkerId = 0;\n\n var TextMarker = function(doc, type) {\n this.lines = [];\n this.type = type;\n this.doc = doc;\n this.id = ++nextMarkerId;\n };\n\n // Clear the marker.\n TextMarker.prototype.clear = function () {\n if (this.explicitlyCleared) { return }\n var cm = this.doc.cm, withOp = cm && !cm.curOp;\n if (withOp) { startOperation(cm); }\n if (hasHandler(this, \"clear\")) {\n var found = this.find();\n if (found) { signalLater(this, \"clear\", found.from, found.to); }\n }\n var min = null, max = null;\n for (var i = 0; i < this.lines.length; ++i) {\n var line = this.lines[i];\n var span = getMarkedSpanFor(line.markedSpans, this);\n if (cm && !this.collapsed) { regLineChange(cm, lineNo(line), \"text\"); }\n else if (cm) {\n if (span.to != null) { max = lineNo(line); }\n if (span.from != null) { min = lineNo(line); }\n }\n line.markedSpans = removeMarkedSpan(line.markedSpans, span);\n if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm)\n { updateLineHeight(line, textHeight(cm.display)); }\n }\n if (cm && this.collapsed && !cm.options.lineWrapping) { for (var i$1 = 0; i$1 < this.lines.length; ++i$1) {\n var visual = visualLine(this.lines[i$1]), len = lineLength(visual);\n if (len > cm.display.maxLineLength) {\n cm.display.maxLine = visual;\n cm.display.maxLineLength = len;\n cm.display.maxLineChanged = true;\n }\n } }\n\n if (min != null && cm && this.collapsed) { regChange(cm, min, max + 1); }\n this.lines.length = 0;\n this.explicitlyCleared = true;\n if (this.atomic && this.doc.cantEdit) {\n this.doc.cantEdit = false;\n if (cm) { reCheckSelection(cm.doc); }\n }\n if (cm) { signalLater(cm, \"markerCleared\", cm, this, min, max); }\n if (withOp) { endOperation(cm); }\n if (this.parent) { this.parent.clear(); }\n };\n\n // Find the position of the marker in the document. Returns a {from,\n // to} object by default. Side can be passed to get a specific side\n // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the\n // Pos objects returned contain a line object, rather than a line\n // number (used to prevent looking up the same line twice).\n TextMarker.prototype.find = function (side, lineObj) {\n if (side == null && this.type == \"bookmark\") { side = 1; }\n var from, to;\n for (var i = 0; i < this.lines.length; ++i) {\n var line = this.lines[i];\n var span = getMarkedSpanFor(line.markedSpans, this);\n if (span.from != null) {\n from = Pos(lineObj ? line : lineNo(line), span.from);\n if (side == -1) { return from }\n }\n if (span.to != null) {\n to = Pos(lineObj ? line : lineNo(line), span.to);\n if (side == 1) { return to }\n }\n }\n return from && {from: from, to: to}\n };\n\n // Signals that the marker's widget changed, and surrounding layout\n // should be recomputed.\n TextMarker.prototype.changed = function () {\n var this$1 = this;\n\n var pos = this.find(-1, true), widget = this, cm = this.doc.cm;\n if (!pos || !cm) { return }\n runInOp(cm, function () {\n var line = pos.line, lineN = lineNo(pos.line);\n var view = findViewForLine(cm, lineN);\n if (view) {\n clearLineMeasurementCacheFor(view);\n cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;\n }\n cm.curOp.updateMaxLine = true;\n if (!lineIsHidden(widget.doc, line) && widget.height != null) {\n var oldHeight = widget.height;\n widget.height = null;\n var dHeight = widgetHeight(widget) - oldHeight;\n if (dHeight)\n { updateLineHeight(line, line.height + dHeight); }\n }\n signalLater(cm, \"markerChanged\", cm, this$1);\n });\n };\n\n TextMarker.prototype.attachLine = function (line) {\n if (!this.lines.length && this.doc.cm) {\n var op = this.doc.cm.curOp;\n if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)\n { (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); }\n }\n this.lines.push(line);\n };\n\n TextMarker.prototype.detachLine = function (line) {\n this.lines.splice(indexOf(this.lines, line), 1);\n if (!this.lines.length && this.doc.cm) {\n var op = this.doc.cm.curOp\n ;(op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);\n }\n };\n eventMixin(TextMarker);\n\n // Create a marker, wire it up to the right lines, and\n function markText(doc, from, to, options, type) {\n // Shared markers (across linked documents) are handled separately\n // (markTextShared will call out to this again, once per\n // document).\n if (options && options.shared) { return markTextShared(doc, from, to, options, type) }\n // Ensure we are in an operation.\n if (doc.cm && !doc.cm.curOp) { return operation(doc.cm, markText)(doc, from, to, options, type) }\n\n var marker = new TextMarker(doc, type), diff = cmp(from, to);\n if (options) { copyObj(options, marker, false); }\n // Don't connect empty markers unless clearWhenEmpty is false\n if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)\n { return marker }\n if (marker.replacedWith) {\n // Showing up as a widget implies collapsed (widget replaces text)\n marker.collapsed = true;\n marker.widgetNode = eltP(\"span\", [marker.replacedWith], \"CodeMirror-widget\");\n if (!options.handleMouseEvents) { marker.widgetNode.setAttribute(\"cm-ignore-events\", \"true\"); }\n if (options.insertLeft) { marker.widgetNode.insertLeft = true; }\n }\n if (marker.collapsed) {\n if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||\n from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))\n { throw new Error(\"Inserting collapsed marker partially overlapping an existing one\") }\n seeCollapsedSpans();\n }\n\n if (marker.addToHistory)\n { addChangeToHistory(doc, {from: from, to: to, origin: \"markText\"}, doc.sel, NaN); }\n\n var curLine = from.line, cm = doc.cm, updateMaxLine;\n doc.iter(curLine, to.line + 1, function (line) {\n if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)\n { updateMaxLine = true; }\n if (marker.collapsed && curLine != from.line) { updateLineHeight(line, 0); }\n addMarkedSpan(line, new MarkedSpan(marker,\n curLine == from.line ? from.ch : null,\n curLine == to.line ? to.ch : null), doc.cm && doc.cm.curOp);\n ++curLine;\n });\n // lineIsHidden depends on the presence of the spans, so needs a second pass\n if (marker.collapsed) { doc.iter(from.line, to.line + 1, function (line) {\n if (lineIsHidden(doc, line)) { updateLineHeight(line, 0); }\n }); }\n\n if (marker.clearOnEnter) { on(marker, \"beforeCursorEnter\", function () { return marker.clear(); }); }\n\n if (marker.readOnly) {\n seeReadOnlySpans();\n if (doc.history.done.length || doc.history.undone.length)\n { doc.clearHistory(); }\n }\n if (marker.collapsed) {\n marker.id = ++nextMarkerId;\n marker.atomic = true;\n }\n if (cm) {\n // Sync editor state\n if (updateMaxLine) { cm.curOp.updateMaxLine = true; }\n if (marker.collapsed)\n { regChange(cm, from.line, to.line + 1); }\n else if (marker.className || marker.startStyle || marker.endStyle || marker.css ||\n marker.attributes || marker.title)\n { for (var i = from.line; i <= to.line; i++) { regLineChange(cm, i, \"text\"); } }\n if (marker.atomic) { reCheckSelection(cm.doc); }\n signalLater(cm, \"markerAdded\", cm, marker);\n }\n return marker\n }\n\n // SHARED TEXTMARKERS\n\n // A shared marker spans multiple linked documents. It is\n // implemented as a meta-marker-object controlling multiple normal\n // markers.\n var SharedTextMarker = function(markers, primary) {\n this.markers = markers;\n this.primary = primary;\n for (var i = 0; i < markers.length; ++i)\n { markers[i].parent = this; }\n };\n\n SharedTextMarker.prototype.clear = function () {\n if (this.explicitlyCleared) { return }\n this.explicitlyCleared = true;\n for (var i = 0; i < this.markers.length; ++i)\n { this.markers[i].clear(); }\n signalLater(this, \"clear\");\n };\n\n SharedTextMarker.prototype.find = function (side, lineObj) {\n return this.primary.find(side, lineObj)\n };\n eventMixin(SharedTextMarker);\n\n function markTextShared(doc, from, to, options, type) {\n options = copyObj(options);\n options.shared = false;\n var markers = [markText(doc, from, to, options, type)], primary = markers[0];\n var widget = options.widgetNode;\n linkedDocs(doc, function (doc) {\n if (widget) { options.widgetNode = widget.cloneNode(true); }\n markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));\n for (var i = 0; i < doc.linked.length; ++i)\n { if (doc.linked[i].isParent) { return } }\n primary = lst(markers);\n });\n return new SharedTextMarker(markers, primary)\n }\n\n function findSharedMarkers(doc) {\n return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function (m) { return m.parent; })\n }\n\n function copySharedMarkers(doc, markers) {\n for (var i = 0; i < markers.length; i++) {\n var marker = markers[i], pos = marker.find();\n var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to);\n if (cmp(mFrom, mTo)) {\n var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type);\n marker.markers.push(subMark);\n subMark.parent = marker;\n }\n }\n }\n\n function detachSharedMarkers(markers) {\n var loop = function ( i ) {\n var marker = markers[i], linked = [marker.primary.doc];\n linkedDocs(marker.primary.doc, function (d) { return linked.push(d); });\n for (var j = 0; j < marker.markers.length; j++) {\n var subMarker = marker.markers[j];\n if (indexOf(linked, subMarker.doc) == -1) {\n subMarker.parent = null;\n marker.markers.splice(j--, 1);\n }\n }\n };\n\n for (var i = 0; i < markers.length; i++) loop( i );\n }\n\n var nextDocId = 0;\n var Doc = function(text, mode, firstLine, lineSep, direction) {\n if (!(this instanceof Doc)) { return new Doc(text, mode, firstLine, lineSep, direction) }\n if (firstLine == null) { firstLine = 0; }\n\n BranchChunk.call(this, [new LeafChunk([new Line(\"\", null)])]);\n this.first = firstLine;\n this.scrollTop = this.scrollLeft = 0;\n this.cantEdit = false;\n this.cleanGeneration = 1;\n this.modeFrontier = this.highlightFrontier = firstLine;\n var start = Pos(firstLine, 0);\n this.sel = simpleSelection(start);\n this.history = new History(null);\n this.id = ++nextDocId;\n this.modeOption = mode;\n this.lineSep = lineSep;\n this.direction = (direction == \"rtl\") ? \"rtl\" : \"ltr\";\n this.extend = false;\n\n if (typeof text == \"string\") { text = this.splitLines(text); }\n updateDoc(this, {from: start, to: start, text: text});\n setSelection(this, simpleSelection(start), sel_dontScroll);\n };\n\n Doc.prototype = createObj(BranchChunk.prototype, {\n constructor: Doc,\n // Iterate over the document. Supports two forms -- with only one\n // argument, it calls that for each line in the document. With\n // three, it iterates over the range given by the first two (with\n // the second being non-inclusive).\n iter: function(from, to, op) {\n if (op) { this.iterN(from - this.first, to - from, op); }\n else { this.iterN(this.first, this.first + this.size, from); }\n },\n\n // Non-public interface for adding and removing lines.\n insert: function(at, lines) {\n var height = 0;\n for (var i = 0; i < lines.length; ++i) { height += lines[i].height; }\n this.insertInner(at - this.first, lines, height);\n },\n remove: function(at, n) { this.removeInner(at - this.first, n); },\n\n // From here, the methods are part of the public interface. Most\n // are also available from CodeMirror (editor) instances.\n\n getValue: function(lineSep) {\n var lines = getLines(this, this.first, this.first + this.size);\n if (lineSep === false) { return lines }\n return lines.join(lineSep || this.lineSeparator())\n },\n setValue: docMethodOp(function(code) {\n var top = Pos(this.first, 0), last = this.first + this.size - 1;\n makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),\n text: this.splitLines(code), origin: \"setValue\", full: true}, true);\n if (this.cm) { scrollToCoords(this.cm, 0, 0); }\n setSelection(this, simpleSelection(top), sel_dontScroll);\n }),\n replaceRange: function(code, from, to, origin) {\n from = clipPos(this, from);\n to = to ? clipPos(this, to) : from;\n replaceRange(this, code, from, to, origin);\n },\n getRange: function(from, to, lineSep) {\n var lines = getBetween(this, clipPos(this, from), clipPos(this, to));\n if (lineSep === false) { return lines }\n if (lineSep === '') { return lines.join('') }\n return lines.join(lineSep || this.lineSeparator())\n },\n\n getLine: function(line) {var l = this.getLineHandle(line); return l && l.text},\n\n getLineHandle: function(line) {if (isLine(this, line)) { return getLine(this, line) }},\n getLineNumber: function(line) {return lineNo(line)},\n\n getLineHandleVisualStart: function(line) {\n if (typeof line == \"number\") { line = getLine(this, line); }\n return visualLine(line)\n },\n\n lineCount: function() {return this.size},\n firstLine: function() {return this.first},\n lastLine: function() {return this.first + this.size - 1},\n\n clipPos: function(pos) {return clipPos(this, pos)},\n\n getCursor: function(start) {\n var range = this.sel.primary(), pos;\n if (start == null || start == \"head\") { pos = range.head; }\n else if (start == \"anchor\") { pos = range.anchor; }\n else if (start == \"end\" || start == \"to\" || start === false) { pos = range.to(); }\n else { pos = range.from(); }\n return pos\n },\n listSelections: function() { return this.sel.ranges },\n somethingSelected: function() {return this.sel.somethingSelected()},\n\n setCursor: docMethodOp(function(line, ch, options) {\n setSimpleSelection(this, clipPos(this, typeof line == \"number\" ? Pos(line, ch || 0) : line), null, options);\n }),\n setSelection: docMethodOp(function(anchor, head, options) {\n setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);\n }),\n extendSelection: docMethodOp(function(head, other, options) {\n extendSelection(this, clipPos(this, head), other && clipPos(this, other), options);\n }),\n extendSelections: docMethodOp(function(heads, options) {\n extendSelections(this, clipPosArray(this, heads), options);\n }),\n extendSelectionsBy: docMethodOp(function(f, options) {\n var heads = map(this.sel.ranges, f);\n extendSelections(this, clipPosArray(this, heads), options);\n }),\n setSelections: docMethodOp(function(ranges, primary, options) {\n if (!ranges.length) { return }\n var out = [];\n for (var i = 0; i < ranges.length; i++)\n { out[i] = new Range(clipPos(this, ranges[i].anchor),\n clipPos(this, ranges[i].head || ranges[i].anchor)); }\n if (primary == null) { primary = Math.min(ranges.length - 1, this.sel.primIndex); }\n setSelection(this, normalizeSelection(this.cm, out, primary), options);\n }),\n addSelection: docMethodOp(function(anchor, head, options) {\n var ranges = this.sel.ranges.slice(0);\n ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));\n setSelection(this, normalizeSelection(this.cm, ranges, ranges.length - 1), options);\n }),\n\n getSelection: function(lineSep) {\n var ranges = this.sel.ranges, lines;\n for (var i = 0; i < ranges.length; i++) {\n var sel = getBetween(this, ranges[i].from(), ranges[i].to());\n lines = lines ? lines.concat(sel) : sel;\n }\n if (lineSep === false) { return lines }\n else { return lines.join(lineSep || this.lineSeparator()) }\n },\n getSelections: function(lineSep) {\n var parts = [], ranges = this.sel.ranges;\n for (var i = 0; i < ranges.length; i++) {\n var sel = getBetween(this, ranges[i].from(), ranges[i].to());\n if (lineSep !== false) { sel = sel.join(lineSep || this.lineSeparator()); }\n parts[i] = sel;\n }\n return parts\n },\n replaceSelection: function(code, collapse, origin) {\n var dup = [];\n for (var i = 0; i < this.sel.ranges.length; i++)\n { dup[i] = code; }\n this.replaceSelections(dup, collapse, origin || \"+input\");\n },\n replaceSelections: docMethodOp(function(code, collapse, origin) {\n var changes = [], sel = this.sel;\n for (var i = 0; i < sel.ranges.length; i++) {\n var range = sel.ranges[i];\n changes[i] = {from: range.from(), to: range.to(), text: this.splitLines(code[i]), origin: origin};\n }\n var newSel = collapse && collapse != \"end\" && computeReplacedSel(this, changes, collapse);\n for (var i$1 = changes.length - 1; i$1 >= 0; i$1--)\n { makeChange(this, changes[i$1]); }\n if (newSel) { setSelectionReplaceHistory(this, newSel); }\n else if (this.cm) { ensureCursorVisible(this.cm); }\n }),\n undo: docMethodOp(function() {makeChangeFromHistory(this, \"undo\");}),\n redo: docMethodOp(function() {makeChangeFromHistory(this, \"redo\");}),\n undoSelection: docMethodOp(function() {makeChangeFromHistory(this, \"undo\", true);}),\n redoSelection: docMethodOp(function() {makeChangeFromHistory(this, \"redo\", true);}),\n\n setExtending: function(val) {this.extend = val;},\n getExtending: function() {return this.extend},\n\n historySize: function() {\n var hist = this.history, done = 0, undone = 0;\n for (var i = 0; i < hist.done.length; i++) { if (!hist.done[i].ranges) { ++done; } }\n for (var i$1 = 0; i$1 < hist.undone.length; i$1++) { if (!hist.undone[i$1].ranges) { ++undone; } }\n return {undo: done, redo: undone}\n },\n clearHistory: function() {\n var this$1 = this;\n\n this.history = new History(this.history);\n linkedDocs(this, function (doc) { return doc.history = this$1.history; }, true);\n },\n\n markClean: function() {\n this.cleanGeneration = this.changeGeneration(true);\n },\n changeGeneration: function(forceSplit) {\n if (forceSplit)\n { this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null; }\n return this.history.generation\n },\n isClean: function (gen) {\n return this.history.generation == (gen || this.cleanGeneration)\n },\n\n getHistory: function() {\n return {done: copyHistoryArray(this.history.done),\n undone: copyHistoryArray(this.history.undone)}\n },\n setHistory: function(histData) {\n var hist = this.history = new History(this.history);\n hist.done = copyHistoryArray(histData.done.slice(0), null, true);\n hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);\n },\n\n setGutterMarker: docMethodOp(function(line, gutterID, value) {\n return changeLine(this, line, \"gutter\", function (line) {\n var markers = line.gutterMarkers || (line.gutterMarkers = {});\n markers[gutterID] = value;\n if (!value && isEmpty(markers)) { line.gutterMarkers = null; }\n return true\n })\n }),\n\n clearGutter: docMethodOp(function(gutterID) {\n var this$1 = this;\n\n this.iter(function (line) {\n if (line.gutterMarkers && line.gutterMarkers[gutterID]) {\n changeLine(this$1, line, \"gutter\", function () {\n line.gutterMarkers[gutterID] = null;\n if (isEmpty(line.gutterMarkers)) { line.gutterMarkers = null; }\n return true\n });\n }\n });\n }),\n\n lineInfo: function(line) {\n var n;\n if (typeof line == \"number\") {\n if (!isLine(this, line)) { return null }\n n = line;\n line = getLine(this, line);\n if (!line) { return null }\n } else {\n n = lineNo(line);\n if (n == null) { return null }\n }\n return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,\n textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,\n widgets: line.widgets}\n },\n\n addLineClass: docMethodOp(function(handle, where, cls) {\n return changeLine(this, handle, where == \"gutter\" ? \"gutter\" : \"class\", function (line) {\n var prop = where == \"text\" ? \"textClass\"\n : where == \"background\" ? \"bgClass\"\n : where == \"gutter\" ? \"gutterClass\" : \"wrapClass\";\n if (!line[prop]) { line[prop] = cls; }\n else if (classTest(cls).test(line[prop])) { return false }\n else { line[prop] += \" \" + cls; }\n return true\n })\n }),\n removeLineClass: docMethodOp(function(handle, where, cls) {\n return changeLine(this, handle, where == \"gutter\" ? \"gutter\" : \"class\", function (line) {\n var prop = where == \"text\" ? \"textClass\"\n : where == \"background\" ? \"bgClass\"\n : where == \"gutter\" ? \"gutterClass\" : \"wrapClass\";\n var cur = line[prop];\n if (!cur) { return false }\n else if (cls == null) { line[prop] = null; }\n else {\n var found = cur.match(classTest(cls));\n if (!found) { return false }\n var end = found.index + found[0].length;\n line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? \"\" : \" \") + cur.slice(end) || null;\n }\n return true\n })\n }),\n\n addLineWidget: docMethodOp(function(handle, node, options) {\n return addLineWidget(this, handle, node, options)\n }),\n removeLineWidget: function(widget) { widget.clear(); },\n\n markText: function(from, to, options) {\n return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || \"range\")\n },\n setBookmark: function(pos, options) {\n var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),\n insertLeft: options && options.insertLeft,\n clearWhenEmpty: false, shared: options && options.shared,\n handleMouseEvents: options && options.handleMouseEvents};\n pos = clipPos(this, pos);\n return markText(this, pos, pos, realOpts, \"bookmark\")\n },\n findMarksAt: function(pos) {\n pos = clipPos(this, pos);\n var markers = [], spans = getLine(this, pos.line).markedSpans;\n if (spans) { for (var i = 0; i < spans.length; ++i) {\n var span = spans[i];\n if ((span.from == null || span.from <= pos.ch) &&\n (span.to == null || span.to >= pos.ch))\n { markers.push(span.marker.parent || span.marker); }\n } }\n return markers\n },\n findMarks: function(from, to, filter) {\n from = clipPos(this, from); to = clipPos(this, to);\n var found = [], lineNo = from.line;\n this.iter(from.line, to.line + 1, function (line) {\n var spans = line.markedSpans;\n if (spans) { for (var i = 0; i < spans.length; i++) {\n var span = spans[i];\n if (!(span.to != null && lineNo == from.line && from.ch >= span.to ||\n span.from == null && lineNo != from.line ||\n span.from != null && lineNo == to.line && span.from >= to.ch) &&\n (!filter || filter(span.marker)))\n { found.push(span.marker.parent || span.marker); }\n } }\n ++lineNo;\n });\n return found\n },\n getAllMarks: function() {\n var markers = [];\n this.iter(function (line) {\n var sps = line.markedSpans;\n if (sps) { for (var i = 0; i < sps.length; ++i)\n { if (sps[i].from != null) { markers.push(sps[i].marker); } } }\n });\n return markers\n },\n\n posFromIndex: function(off) {\n var ch, lineNo = this.first, sepSize = this.lineSeparator().length;\n this.iter(function (line) {\n var sz = line.text.length + sepSize;\n if (sz > off) { ch = off; return true }\n off -= sz;\n ++lineNo;\n });\n return clipPos(this, Pos(lineNo, ch))\n },\n indexFromPos: function (coords) {\n coords = clipPos(this, coords);\n var index = coords.ch;\n if (coords.line < this.first || coords.ch < 0) { return 0 }\n var sepSize = this.lineSeparator().length;\n this.iter(this.first, coords.line, function (line) { // iter aborts when callback returns a truthy value\n index += line.text.length + sepSize;\n });\n return index\n },\n\n copy: function(copyHistory) {\n var doc = new Doc(getLines(this, this.first, this.first + this.size),\n this.modeOption, this.first, this.lineSep, this.direction);\n doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;\n doc.sel = this.sel;\n doc.extend = false;\n if (copyHistory) {\n doc.history.undoDepth = this.history.undoDepth;\n doc.setHistory(this.getHistory());\n }\n return doc\n },\n\n linkedDoc: function(options) {\n if (!options) { options = {}; }\n var from = this.first, to = this.first + this.size;\n if (options.from != null && options.from > from) { from = options.from; }\n if (options.to != null && options.to < to) { to = options.to; }\n var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep, this.direction);\n if (options.sharedHist) { copy.history = this.history\n ; }(this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});\n copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];\n copySharedMarkers(copy, findSharedMarkers(this));\n return copy\n },\n unlinkDoc: function(other) {\n if (other instanceof CodeMirror) { other = other.doc; }\n if (this.linked) { for (var i = 0; i < this.linked.length; ++i) {\n var link = this.linked[i];\n if (link.doc != other) { continue }\n this.linked.splice(i, 1);\n other.unlinkDoc(this);\n detachSharedMarkers(findSharedMarkers(this));\n break\n } }\n // If the histories were shared, split them again\n if (other.history == this.history) {\n var splitIds = [other.id];\n linkedDocs(other, function (doc) { return splitIds.push(doc.id); }, true);\n other.history = new History(null);\n other.history.done = copyHistoryArray(this.history.done, splitIds);\n other.history.undone = copyHistoryArray(this.history.undone, splitIds);\n }\n },\n iterLinkedDocs: function(f) {linkedDocs(this, f);},\n\n getMode: function() {return this.mode},\n getEditor: function() {return this.cm},\n\n splitLines: function(str) {\n if (this.lineSep) { return str.split(this.lineSep) }\n return splitLinesAuto(str)\n },\n lineSeparator: function() { return this.lineSep || \"\\n\" },\n\n setDirection: docMethodOp(function (dir) {\n if (dir != \"rtl\") { dir = \"ltr\"; }\n if (dir == this.direction) { return }\n this.direction = dir;\n this.iter(function (line) { return line.order = null; });\n if (this.cm) { directionChanged(this.cm); }\n })\n });\n\n // Public alias.\n Doc.prototype.eachLine = Doc.prototype.iter;\n\n // Kludge to work around strange IE behavior where it'll sometimes\n // re-fire a series of drag-related events right after the drop (#1551)\n var lastDrop = 0;\n\n function onDrop(e) {\n var cm = this;\n clearDragCursor(cm);\n if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))\n { return }\n e_preventDefault(e);\n if (ie) { lastDrop = +new Date; }\n var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;\n if (!pos || cm.isReadOnly()) { return }\n // Might be a file drop, in which case we simply extract the text\n // and insert it.\n if (files && files.length && window.FileReader && window.File) {\n var n = files.length, text = Array(n), read = 0;\n var markAsReadAndPasteIfAllFilesAreRead = function () {\n if (++read == n) {\n operation(cm, function () {\n pos = clipPos(cm.doc, pos);\n var change = {from: pos, to: pos,\n text: cm.doc.splitLines(\n text.filter(function (t) { return t != null; }).join(cm.doc.lineSeparator())),\n origin: \"paste\"};\n makeChange(cm.doc, change);\n setSelectionReplaceHistory(cm.doc, simpleSelection(clipPos(cm.doc, pos), clipPos(cm.doc, changeEnd(change))));\n })();\n }\n };\n var readTextFromFile = function (file, i) {\n if (cm.options.allowDropFileTypes &&\n indexOf(cm.options.allowDropFileTypes, file.type) == -1) {\n markAsReadAndPasteIfAllFilesAreRead();\n return\n }\n var reader = new FileReader;\n reader.onerror = function () { return markAsReadAndPasteIfAllFilesAreRead(); };\n reader.onload = function () {\n var content = reader.result;\n if (/[\\x00-\\x08\\x0e-\\x1f]{2}/.test(content)) {\n markAsReadAndPasteIfAllFilesAreRead();\n return\n }\n text[i] = content;\n markAsReadAndPasteIfAllFilesAreRead();\n };\n reader.readAsText(file);\n };\n for (var i = 0; i < files.length; i++) { readTextFromFile(files[i], i); }\n } else { // Normal drop\n // Don't do a replace if the drop happened inside of the selected text.\n if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {\n cm.state.draggingText(e);\n // Ensure the editor is re-focused\n setTimeout(function () { return cm.display.input.focus(); }, 20);\n return\n }\n try {\n var text$1 = e.dataTransfer.getData(\"Text\");\n if (text$1) {\n var selected;\n if (cm.state.draggingText && !cm.state.draggingText.copy)\n { selected = cm.listSelections(); }\n setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));\n if (selected) { for (var i$1 = 0; i$1 < selected.length; ++i$1)\n { replaceRange(cm.doc, \"\", selected[i$1].anchor, selected[i$1].head, \"drag\"); } }\n cm.replaceSelection(text$1, \"around\", \"paste\");\n cm.display.input.focus();\n }\n }\n catch(e$1){}\n }\n }\n\n function onDragStart(cm, e) {\n if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return }\n if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { return }\n\n e.dataTransfer.setData(\"Text\", cm.getSelection());\n e.dataTransfer.effectAllowed = \"copyMove\";\n\n // Use dummy image instead of default browsers image.\n // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.\n if (e.dataTransfer.setDragImage && !safari) {\n var img = elt(\"img\", null, null, \"position: fixed; left: 0; top: 0;\");\n img.src = \"data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==\";\n if (presto) {\n img.width = img.height = 1;\n cm.display.wrapper.appendChild(img);\n // Force a relayout, or Opera won't use our image for some obscure reason\n img._top = img.offsetTop;\n }\n e.dataTransfer.setDragImage(img, 0, 0);\n if (presto) { img.parentNode.removeChild(img); }\n }\n }\n\n function onDragOver(cm, e) {\n var pos = posFromMouse(cm, e);\n if (!pos) { return }\n var frag = document.createDocumentFragment();\n drawSelectionCursor(cm, pos, frag);\n if (!cm.display.dragCursor) {\n cm.display.dragCursor = elt(\"div\", null, \"CodeMirror-cursors CodeMirror-dragcursors\");\n cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv);\n }\n removeChildrenAndAdd(cm.display.dragCursor, frag);\n }\n\n function clearDragCursor(cm) {\n if (cm.display.dragCursor) {\n cm.display.lineSpace.removeChild(cm.display.dragCursor);\n cm.display.dragCursor = null;\n }\n }\n\n // These must be handled carefully, because naively registering a\n // handler for each editor will cause the editors to never be\n // garbage collected.\n\n function forEachCodeMirror(f) {\n if (!document.getElementsByClassName) { return }\n var byClass = document.getElementsByClassName(\"CodeMirror\"), editors = [];\n for (var i = 0; i < byClass.length; i++) {\n var cm = byClass[i].CodeMirror;\n if (cm) { editors.push(cm); }\n }\n if (editors.length) { editors[0].operation(function () {\n for (var i = 0; i < editors.length; i++) { f(editors[i]); }\n }); }\n }\n\n var globalsRegistered = false;\n function ensureGlobalHandlers() {\n if (globalsRegistered) { return }\n registerGlobalHandlers();\n globalsRegistered = true;\n }\n function registerGlobalHandlers() {\n // When the window resizes, we need to refresh active editors.\n var resizeTimer;\n on(window, \"resize\", function () {\n if (resizeTimer == null) { resizeTimer = setTimeout(function () {\n resizeTimer = null;\n forEachCodeMirror(onResize);\n }, 100); }\n });\n // When the window loses focus, we want to show the editor as blurred\n on(window, \"blur\", function () { return forEachCodeMirror(onBlur); });\n }\n // Called when the window resizes\n function onResize(cm) {\n var d = cm.display;\n // Might be a text scaling operation, clear size caches.\n d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;\n d.scrollbarsClipped = false;\n cm.setSize();\n }\n\n var keyNames = {\n 3: \"Pause\", 8: \"Backspace\", 9: \"Tab\", 13: \"Enter\", 16: \"Shift\", 17: \"Ctrl\", 18: \"Alt\",\n 19: \"Pause\", 20: \"CapsLock\", 27: \"Esc\", 32: \"Space\", 33: \"PageUp\", 34: \"PageDown\", 35: \"End\",\n 36: \"Home\", 37: \"Left\", 38: \"Up\", 39: \"Right\", 40: \"Down\", 44: \"PrintScrn\", 45: \"Insert\",\n 46: \"Delete\", 59: \";\", 61: \"=\", 91: \"Mod\", 92: \"Mod\", 93: \"Mod\",\n 106: \"*\", 107: \"=\", 109: \"-\", 110: \".\", 111: \"/\", 145: \"ScrollLock\",\n 173: \"-\", 186: \";\", 187: \"=\", 188: \",\", 189: \"-\", 190: \".\", 191: \"/\", 192: \"`\", 219: \"[\", 220: \"\\\\\",\n 221: \"]\", 222: \"'\", 224: \"Mod\", 63232: \"Up\", 63233: \"Down\", 63234: \"Left\", 63235: \"Right\", 63272: \"Delete\",\n 63273: \"Home\", 63275: \"End\", 63276: \"PageUp\", 63277: \"PageDown\", 63302: \"Insert\"\n };\n\n // Number keys\n for (var i = 0; i < 10; i++) { keyNames[i + 48] = keyNames[i + 96] = String(i); }\n // Alphabetic keys\n for (var i$1 = 65; i$1 <= 90; i$1++) { keyNames[i$1] = String.fromCharCode(i$1); }\n // Function keys\n for (var i$2 = 1; i$2 <= 12; i$2++) { keyNames[i$2 + 111] = keyNames[i$2 + 63235] = \"F\" + i$2; }\n\n var keyMap = {};\n\n keyMap.basic = {\n \"Left\": \"goCharLeft\", \"Right\": \"goCharRight\", \"Up\": \"goLineUp\", \"Down\": \"goLineDown\",\n \"End\": \"goLineEnd\", \"Home\": \"goLineStartSmart\", \"PageUp\": \"goPageUp\", \"PageDown\": \"goPageDown\",\n \"Delete\": \"delCharAfter\", \"Backspace\": \"delCharBefore\", \"Shift-Backspace\": \"delCharBefore\",\n \"Tab\": \"defaultTab\", \"Shift-Tab\": \"indentAuto\",\n \"Enter\": \"newlineAndIndent\", \"Insert\": \"toggleOverwrite\",\n \"Esc\": \"singleSelection\"\n };\n // Note that the save and find-related commands aren't defined by\n // default. User code or addons can define them. Unknown commands\n // are simply ignored.\n keyMap.pcDefault = {\n \"Ctrl-A\": \"selectAll\", \"Ctrl-D\": \"deleteLine\", \"Ctrl-Z\": \"undo\", \"Shift-Ctrl-Z\": \"redo\", \"Ctrl-Y\": \"redo\",\n \"Ctrl-Home\": \"goDocStart\", \"Ctrl-End\": \"goDocEnd\", \"Ctrl-Up\": \"goLineUp\", \"Ctrl-Down\": \"goLineDown\",\n \"Ctrl-Left\": \"goGroupLeft\", \"Ctrl-Right\": \"goGroupRight\", \"Alt-Left\": \"goLineStart\", \"Alt-Right\": \"goLineEnd\",\n \"Ctrl-Backspace\": \"delGroupBefore\", \"Ctrl-Delete\": \"delGroupAfter\", \"Ctrl-S\": \"save\", \"Ctrl-F\": \"find\",\n \"Ctrl-G\": \"findNext\", \"Shift-Ctrl-G\": \"findPrev\", \"Shift-Ctrl-F\": \"replace\", \"Shift-Ctrl-R\": \"replaceAll\",\n \"Ctrl-[\": \"indentLess\", \"Ctrl-]\": \"indentMore\",\n \"Ctrl-U\": \"undoSelection\", \"Shift-Ctrl-U\": \"redoSelection\", \"Alt-U\": \"redoSelection\",\n \"fallthrough\": \"basic\"\n };\n // Very basic readline/emacs-style bindings, which are standard on Mac.\n keyMap.emacsy = {\n \"Ctrl-F\": \"goCharRight\", \"Ctrl-B\": \"goCharLeft\", \"Ctrl-P\": \"goLineUp\", \"Ctrl-N\": \"goLineDown\",\n \"Ctrl-A\": \"goLineStart\", \"Ctrl-E\": \"goLineEnd\", \"Ctrl-V\": \"goPageDown\", \"Shift-Ctrl-V\": \"goPageUp\",\n \"Ctrl-D\": \"delCharAfter\", \"Ctrl-H\": \"delCharBefore\", \"Alt-Backspace\": \"delWordBefore\", \"Ctrl-K\": \"killLine\",\n \"Ctrl-T\": \"transposeChars\", \"Ctrl-O\": \"openLine\"\n };\n keyMap.macDefault = {\n \"Cmd-A\": \"selectAll\", \"Cmd-D\": \"deleteLine\", \"Cmd-Z\": \"undo\", \"Shift-Cmd-Z\": \"redo\", \"Cmd-Y\": \"redo\",\n \"Cmd-Home\": \"goDocStart\", \"Cmd-Up\": \"goDocStart\", \"Cmd-End\": \"goDocEnd\", \"Cmd-Down\": \"goDocEnd\", \"Alt-Left\": \"goGroupLeft\",\n \"Alt-Right\": \"goGroupRight\", \"Cmd-Left\": \"goLineLeft\", \"Cmd-Right\": \"goLineRight\", \"Alt-Backspace\": \"delGroupBefore\",\n \"Ctrl-Alt-Backspace\": \"delGroupAfter\", \"Alt-Delete\": \"delGroupAfter\", \"Cmd-S\": \"save\", \"Cmd-F\": \"find\",\n \"Cmd-G\": \"findNext\", \"Shift-Cmd-G\": \"findPrev\", \"Cmd-Alt-F\": \"replace\", \"Shift-Cmd-Alt-F\": \"replaceAll\",\n \"Cmd-[\": \"indentLess\", \"Cmd-]\": \"indentMore\", \"Cmd-Backspace\": \"delWrappedLineLeft\", \"Cmd-Delete\": \"delWrappedLineRight\",\n \"Cmd-U\": \"undoSelection\", \"Shift-Cmd-U\": \"redoSelection\", \"Ctrl-Up\": \"goDocStart\", \"Ctrl-Down\": \"goDocEnd\",\n \"fallthrough\": [\"basic\", \"emacsy\"]\n };\n keyMap[\"default\"] = mac ? keyMap.macDefault : keyMap.pcDefault;\n\n // KEYMAP DISPATCH\n\n function normalizeKeyName(name) {\n var parts = name.split(/-(?!$)/);\n name = parts[parts.length - 1];\n var alt, ctrl, shift, cmd;\n for (var i = 0; i < parts.length - 1; i++) {\n var mod = parts[i];\n if (/^(cmd|meta|m)$/i.test(mod)) { cmd = true; }\n else if (/^a(lt)?$/i.test(mod)) { alt = true; }\n else if (/^(c|ctrl|control)$/i.test(mod)) { ctrl = true; }\n else if (/^s(hift)?$/i.test(mod)) { shift = true; }\n else { throw new Error(\"Unrecognized modifier name: \" + mod) }\n }\n if (alt) { name = \"Alt-\" + name; }\n if (ctrl) { name = \"Ctrl-\" + name; }\n if (cmd) { name = \"Cmd-\" + name; }\n if (shift) { name = \"Shift-\" + name; }\n return name\n }\n\n // This is a kludge to keep keymaps mostly working as raw objects\n // (backwards compatibility) while at the same time support features\n // like normalization and multi-stroke key bindings. It compiles a\n // new normalized keymap, and then updates the old object to reflect\n // this.\n function normalizeKeyMap(keymap) {\n var copy = {};\n for (var keyname in keymap) { if (keymap.hasOwnProperty(keyname)) {\n var value = keymap[keyname];\n if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { continue }\n if (value == \"...\") { delete keymap[keyname]; continue }\n\n var keys = map(keyname.split(\" \"), normalizeKeyName);\n for (var i = 0; i < keys.length; i++) {\n var val = (void 0), name = (void 0);\n if (i == keys.length - 1) {\n name = keys.join(\" \");\n val = value;\n } else {\n name = keys.slice(0, i + 1).join(\" \");\n val = \"...\";\n }\n var prev = copy[name];\n if (!prev) { copy[name] = val; }\n else if (prev != val) { throw new Error(\"Inconsistent bindings for \" + name) }\n }\n delete keymap[keyname];\n } }\n for (var prop in copy) { keymap[prop] = copy[prop]; }\n return keymap\n }\n\n function lookupKey(key, map, handle, context) {\n map = getKeyMap(map);\n var found = map.call ? map.call(key, context) : map[key];\n if (found === false) { return \"nothing\" }\n if (found === \"...\") { return \"multi\" }\n if (found != null && handle(found)) { return \"handled\" }\n\n if (map.fallthrough) {\n if (Object.prototype.toString.call(map.fallthrough) != \"[object Array]\")\n { return lookupKey(key, map.fallthrough, handle, context) }\n for (var i = 0; i < map.fallthrough.length; i++) {\n var result = lookupKey(key, map.fallthrough[i], handle, context);\n if (result) { return result }\n }\n }\n }\n\n // Modifier key presses don't count as 'real' key presses for the\n // purpose of keymap fallthrough.\n function isModifierKey(value) {\n var name = typeof value == \"string\" ? value : keyNames[value.keyCode];\n return name == \"Ctrl\" || name == \"Alt\" || name == \"Shift\" || name == \"Mod\"\n }\n\n function addModifierNames(name, event, noShift) {\n var base = name;\n if (event.altKey && base != \"Alt\") { name = \"Alt-\" + name; }\n if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != \"Ctrl\") { name = \"Ctrl-\" + name; }\n if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != \"Mod\") { name = \"Cmd-\" + name; }\n if (!noShift && event.shiftKey && base != \"Shift\") { name = \"Shift-\" + name; }\n return name\n }\n\n // Look up the name of a key as indicated by an event object.\n function keyName(event, noShift) {\n if (presto && event.keyCode == 34 && event[\"char\"]) { return false }\n var name = keyNames[event.keyCode];\n if (name == null || event.altGraphKey) { return false }\n // Ctrl-ScrollLock has keyCode 3, same as Ctrl-Pause,\n // so we'll use event.code when available (Chrome 48+, FF 38+, Safari 10.1+)\n if (event.keyCode == 3 && event.code) { name = event.code; }\n return addModifierNames(name, event, noShift)\n }\n\n function getKeyMap(val) {\n return typeof val == \"string\" ? keyMap[val] : val\n }\n\n // Helper for deleting text near the selection(s), used to implement\n // backspace, delete, and similar functionality.\n function deleteNearSelection(cm, compute) {\n var ranges = cm.doc.sel.ranges, kill = [];\n // Build up a set of ranges to kill first, merging overlapping\n // ranges.\n for (var i = 0; i < ranges.length; i++) {\n var toKill = compute(ranges[i]);\n while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {\n var replaced = kill.pop();\n if (cmp(replaced.from, toKill.from) < 0) {\n toKill.from = replaced.from;\n break\n }\n }\n kill.push(toKill);\n }\n // Next, remove those actual ranges.\n runInOp(cm, function () {\n for (var i = kill.length - 1; i >= 0; i--)\n { replaceRange(cm.doc, \"\", kill[i].from, kill[i].to, \"+delete\"); }\n ensureCursorVisible(cm);\n });\n }\n\n function moveCharLogically(line, ch, dir) {\n var target = skipExtendingChars(line.text, ch + dir, dir);\n return target < 0 || target > line.text.length ? null : target\n }\n\n function moveLogically(line, start, dir) {\n var ch = moveCharLogically(line, start.ch, dir);\n return ch == null ? null : new Pos(start.line, ch, dir < 0 ? \"after\" : \"before\")\n }\n\n function endOfLine(visually, cm, lineObj, lineNo, dir) {\n if (visually) {\n if (cm.doc.direction == \"rtl\") { dir = -dir; }\n var order = getOrder(lineObj, cm.doc.direction);\n if (order) {\n var part = dir < 0 ? lst(order) : order[0];\n var moveInStorageOrder = (dir < 0) == (part.level == 1);\n var sticky = moveInStorageOrder ? \"after\" : \"before\";\n var ch;\n // With a wrapped rtl chunk (possibly spanning multiple bidi parts),\n // it could be that the last bidi part is not on the last visual line,\n // since visual lines contain content order-consecutive chunks.\n // Thus, in rtl, we are looking for the first (content-order) character\n // in the rtl chunk that is on the last line (that is, the same line\n // as the last (content-order) character).\n if (part.level > 0 || cm.doc.direction == \"rtl\") {\n var prep = prepareMeasureForLine(cm, lineObj);\n ch = dir < 0 ? lineObj.text.length - 1 : 0;\n var targetTop = measureCharPrepared(cm, prep, ch).top;\n ch = findFirst(function (ch) { return measureCharPrepared(cm, prep, ch).top == targetTop; }, (dir < 0) == (part.level == 1) ? part.from : part.to - 1, ch);\n if (sticky == \"before\") { ch = moveCharLogically(lineObj, ch, 1); }\n } else { ch = dir < 0 ? part.to : part.from; }\n return new Pos(lineNo, ch, sticky)\n }\n }\n return new Pos(lineNo, dir < 0 ? lineObj.text.length : 0, dir < 0 ? \"before\" : \"after\")\n }\n\n function moveVisually(cm, line, start, dir) {\n var bidi = getOrder(line, cm.doc.direction);\n if (!bidi) { return moveLogically(line, start, dir) }\n if (start.ch >= line.text.length) {\n start.ch = line.text.length;\n start.sticky = \"before\";\n } else if (start.ch <= 0) {\n start.ch = 0;\n start.sticky = \"after\";\n }\n var partPos = getBidiPartAt(bidi, start.ch, start.sticky), part = bidi[partPos];\n if (cm.doc.direction == \"ltr\" && part.level % 2 == 0 && (dir > 0 ? part.to > start.ch : part.from < start.ch)) {\n // Case 1: We move within an ltr part in an ltr editor. Even with wrapped lines,\n // nothing interesting happens.\n return moveLogically(line, start, dir)\n }\n\n var mv = function (pos, dir) { return moveCharLogically(line, pos instanceof Pos ? pos.ch : pos, dir); };\n var prep;\n var getWrappedLineExtent = function (ch) {\n if (!cm.options.lineWrapping) { return {begin: 0, end: line.text.length} }\n prep = prep || prepareMeasureForLine(cm, line);\n return wrappedLineExtentChar(cm, line, prep, ch)\n };\n var wrappedLineExtent = getWrappedLineExtent(start.sticky == \"before\" ? mv(start, -1) : start.ch);\n\n if (cm.doc.direction == \"rtl\" || part.level == 1) {\n var moveInStorageOrder = (part.level == 1) == (dir < 0);\n var ch = mv(start, moveInStorageOrder ? 1 : -1);\n if (ch != null && (!moveInStorageOrder ? ch >= part.from && ch >= wrappedLineExtent.begin : ch <= part.to && ch <= wrappedLineExtent.end)) {\n // Case 2: We move within an rtl part or in an rtl editor on the same visual line\n var sticky = moveInStorageOrder ? \"before\" : \"after\";\n return new Pos(start.line, ch, sticky)\n }\n }\n\n // Case 3: Could not move within this bidi part in this visual line, so leave\n // the current bidi part\n\n var searchInVisualLine = function (partPos, dir, wrappedLineExtent) {\n var getRes = function (ch, moveInStorageOrder) { return moveInStorageOrder\n ? new Pos(start.line, mv(ch, 1), \"before\")\n : new Pos(start.line, ch, \"after\"); };\n\n for (; partPos >= 0 && partPos < bidi.length; partPos += dir) {\n var part = bidi[partPos];\n var moveInStorageOrder = (dir > 0) == (part.level != 1);\n var ch = moveInStorageOrder ? wrappedLineExtent.begin : mv(wrappedLineExtent.end, -1);\n if (part.from <= ch && ch < part.to) { return getRes(ch, moveInStorageOrder) }\n ch = moveInStorageOrder ? part.from : mv(part.to, -1);\n if (wrappedLineExtent.begin <= ch && ch < wrappedLineExtent.end) { return getRes(ch, moveInStorageOrder) }\n }\n };\n\n // Case 3a: Look for other bidi parts on the same visual line\n var res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent);\n if (res) { return res }\n\n // Case 3b: Look for other bidi parts on the next visual line\n var nextCh = dir > 0 ? wrappedLineExtent.end : mv(wrappedLineExtent.begin, -1);\n if (nextCh != null && !(dir > 0 && nextCh == line.text.length)) {\n res = searchInVisualLine(dir > 0 ? 0 : bidi.length - 1, dir, getWrappedLineExtent(nextCh));\n if (res) { return res }\n }\n\n // Case 4: Nowhere to move\n return null\n }\n\n // Commands are parameter-less actions that can be performed on an\n // editor, mostly used for keybindings.\n var commands = {\n selectAll: selectAll,\n singleSelection: function (cm) { return cm.setSelection(cm.getCursor(\"anchor\"), cm.getCursor(\"head\"), sel_dontScroll); },\n killLine: function (cm) { return deleteNearSelection(cm, function (range) {\n if (range.empty()) {\n var len = getLine(cm.doc, range.head.line).text.length;\n if (range.head.ch == len && range.head.line < cm.lastLine())\n { return {from: range.head, to: Pos(range.head.line + 1, 0)} }\n else\n { return {from: range.head, to: Pos(range.head.line, len)} }\n } else {\n return {from: range.from(), to: range.to()}\n }\n }); },\n deleteLine: function (cm) { return deleteNearSelection(cm, function (range) { return ({\n from: Pos(range.from().line, 0),\n to: clipPos(cm.doc, Pos(range.to().line + 1, 0))\n }); }); },\n delLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { return ({\n from: Pos(range.from().line, 0), to: range.from()\n }); }); },\n delWrappedLineLeft: function (cm) { return deleteNearSelection(cm, function (range) {\n var top = cm.charCoords(range.head, \"div\").top + 5;\n var leftPos = cm.coordsChar({left: 0, top: top}, \"div\");\n return {from: leftPos, to: range.from()}\n }); },\n delWrappedLineRight: function (cm) { return deleteNearSelection(cm, function (range) {\n var top = cm.charCoords(range.head, \"div\").top + 5;\n var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, \"div\");\n return {from: range.from(), to: rightPos }\n }); },\n undo: function (cm) { return cm.undo(); },\n redo: function (cm) { return cm.redo(); },\n undoSelection: function (cm) { return cm.undoSelection(); },\n redoSelection: function (cm) { return cm.redoSelection(); },\n goDocStart: function (cm) { return cm.extendSelection(Pos(cm.firstLine(), 0)); },\n goDocEnd: function (cm) { return cm.extendSelection(Pos(cm.lastLine())); },\n goLineStart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStart(cm, range.head.line); },\n {origin: \"+move\", bias: 1}\n ); },\n goLineStartSmart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStartSmart(cm, range.head); },\n {origin: \"+move\", bias: 1}\n ); },\n goLineEnd: function (cm) { return cm.extendSelectionsBy(function (range) { return lineEnd(cm, range.head.line); },\n {origin: \"+move\", bias: -1}\n ); },\n goLineRight: function (cm) { return cm.extendSelectionsBy(function (range) {\n var top = cm.cursorCoords(range.head, \"div\").top + 5;\n return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, \"div\")\n }, sel_move); },\n goLineLeft: function (cm) { return cm.extendSelectionsBy(function (range) {\n var top = cm.cursorCoords(range.head, \"div\").top + 5;\n return cm.coordsChar({left: 0, top: top}, \"div\")\n }, sel_move); },\n goLineLeftSmart: function (cm) { return cm.extendSelectionsBy(function (range) {\n var top = cm.cursorCoords(range.head, \"div\").top + 5;\n var pos = cm.coordsChar({left: 0, top: top}, \"div\");\n if (pos.ch < cm.getLine(pos.line).search(/\\S/)) { return lineStartSmart(cm, range.head) }\n return pos\n }, sel_move); },\n goLineUp: function (cm) { return cm.moveV(-1, \"line\"); },\n goLineDown: function (cm) { return cm.moveV(1, \"line\"); },\n goPageUp: function (cm) { return cm.moveV(-1, \"page\"); },\n goPageDown: function (cm) { return cm.moveV(1, \"page\"); },\n goCharLeft: function (cm) { return cm.moveH(-1, \"char\"); },\n goCharRight: function (cm) { return cm.moveH(1, \"char\"); },\n goColumnLeft: function (cm) { return cm.moveH(-1, \"column\"); },\n goColumnRight: function (cm) { return cm.moveH(1, \"column\"); },\n goWordLeft: function (cm) { return cm.moveH(-1, \"word\"); },\n goGroupRight: function (cm) { return cm.moveH(1, \"group\"); },\n goGroupLeft: function (cm) { return cm.moveH(-1, \"group\"); },\n goWordRight: function (cm) { return cm.moveH(1, \"word\"); },\n delCharBefore: function (cm) { return cm.deleteH(-1, \"codepoint\"); },\n delCharAfter: function (cm) { return cm.deleteH(1, \"char\"); },\n delWordBefore: function (cm) { return cm.deleteH(-1, \"word\"); },\n delWordAfter: function (cm) { return cm.deleteH(1, \"word\"); },\n delGroupBefore: function (cm) { return cm.deleteH(-1, \"group\"); },\n delGroupAfter: function (cm) { return cm.deleteH(1, \"group\"); },\n indentAuto: function (cm) { return cm.indentSelection(\"smart\"); },\n indentMore: function (cm) { return cm.indentSelection(\"add\"); },\n indentLess: function (cm) { return cm.indentSelection(\"subtract\"); },\n insertTab: function (cm) { return cm.replaceSelection(\"\\t\"); },\n insertSoftTab: function (cm) {\n var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize;\n for (var i = 0; i < ranges.length; i++) {\n var pos = ranges[i].from();\n var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);\n spaces.push(spaceStr(tabSize - col % tabSize));\n }\n cm.replaceSelections(spaces);\n },\n defaultTab: function (cm) {\n if (cm.somethingSelected()) { cm.indentSelection(\"add\"); }\n else { cm.execCommand(\"insertTab\"); }\n },\n // Swap the two chars left and right of each selection's head.\n // Move cursor behind the two swapped characters afterwards.\n //\n // Doesn't consider line feeds a character.\n // Doesn't scan more than one line above to find a character.\n // Doesn't do anything on an empty line.\n // Doesn't do anything with non-empty selections.\n transposeChars: function (cm) { return runInOp(cm, function () {\n var ranges = cm.listSelections(), newSel = [];\n for (var i = 0; i < ranges.length; i++) {\n if (!ranges[i].empty()) { continue }\n var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text;\n if (line) {\n if (cur.ch == line.length) { cur = new Pos(cur.line, cur.ch - 1); }\n if (cur.ch > 0) {\n cur = new Pos(cur.line, cur.ch + 1);\n cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),\n Pos(cur.line, cur.ch - 2), cur, \"+transpose\");\n } else if (cur.line > cm.doc.first) {\n var prev = getLine(cm.doc, cur.line - 1).text;\n if (prev) {\n cur = new Pos(cur.line, 1);\n cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() +\n prev.charAt(prev.length - 1),\n Pos(cur.line - 1, prev.length - 1), cur, \"+transpose\");\n }\n }\n }\n newSel.push(new Range(cur, cur));\n }\n cm.setSelections(newSel);\n }); },\n newlineAndIndent: function (cm) { return runInOp(cm, function () {\n var sels = cm.listSelections();\n for (var i = sels.length - 1; i >= 0; i--)\n { cm.replaceRange(cm.doc.lineSeparator(), sels[i].anchor, sels[i].head, \"+input\"); }\n sels = cm.listSelections();\n for (var i$1 = 0; i$1 < sels.length; i$1++)\n { cm.indentLine(sels[i$1].from().line, null, true); }\n ensureCursorVisible(cm);\n }); },\n openLine: function (cm) { return cm.replaceSelection(\"\\n\", \"start\"); },\n toggleOverwrite: function (cm) { return cm.toggleOverwrite(); }\n };\n\n\n function lineStart(cm, lineN) {\n var line = getLine(cm.doc, lineN);\n var visual = visualLine(line);\n if (visual != line) { lineN = lineNo(visual); }\n return endOfLine(true, cm, visual, lineN, 1)\n }\n function lineEnd(cm, lineN) {\n var line = getLine(cm.doc, lineN);\n var visual = visualLineEnd(line);\n if (visual != line) { lineN = lineNo(visual); }\n return endOfLine(true, cm, line, lineN, -1)\n }\n function lineStartSmart(cm, pos) {\n var start = lineStart(cm, pos.line);\n var line = getLine(cm.doc, start.line);\n var order = getOrder(line, cm.doc.direction);\n if (!order || order[0].level == 0) {\n var firstNonWS = Math.max(start.ch, line.text.search(/\\S/));\n var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch;\n return Pos(start.line, inWS ? 0 : firstNonWS, start.sticky)\n }\n return start\n }\n\n // Run a handler that was bound to a key.\n function doHandleBinding(cm, bound, dropShift) {\n if (typeof bound == \"string\") {\n bound = commands[bound];\n if (!bound) { return false }\n }\n // Ensure previous input has been read, so that the handler sees a\n // consistent view of the document\n cm.display.input.ensurePolled();\n var prevShift = cm.display.shift, done = false;\n try {\n if (cm.isReadOnly()) { cm.state.suppressEdits = true; }\n if (dropShift) { cm.display.shift = false; }\n done = bound(cm) != Pass;\n } finally {\n cm.display.shift = prevShift;\n cm.state.suppressEdits = false;\n }\n return done\n }\n\n function lookupKeyForEditor(cm, name, handle) {\n for (var i = 0; i < cm.state.keyMaps.length; i++) {\n var result = lookupKey(name, cm.state.keyMaps[i], handle, cm);\n if (result) { return result }\n }\n return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm))\n || lookupKey(name, cm.options.keyMap, handle, cm)\n }\n\n // Note that, despite the name, this function is also used to check\n // for bound mouse clicks.\n\n var stopSeq = new Delayed;\n\n function dispatchKey(cm, name, e, handle) {\n var seq = cm.state.keySeq;\n if (seq) {\n if (isModifierKey(name)) { return \"handled\" }\n if (/\\'$/.test(name))\n { cm.state.keySeq = null; }\n else\n { stopSeq.set(50, function () {\n if (cm.state.keySeq == seq) {\n cm.state.keySeq = null;\n cm.display.input.reset();\n }\n }); }\n if (dispatchKeyInner(cm, seq + \" \" + name, e, handle)) { return true }\n }\n return dispatchKeyInner(cm, name, e, handle)\n }\n\n function dispatchKeyInner(cm, name, e, handle) {\n var result = lookupKeyForEditor(cm, name, handle);\n\n if (result == \"multi\")\n { cm.state.keySeq = name; }\n if (result == \"handled\")\n { signalLater(cm, \"keyHandled\", cm, name, e); }\n\n if (result == \"handled\" || result == \"multi\") {\n e_preventDefault(e);\n restartBlink(cm);\n }\n\n return !!result\n }\n\n // Handle a key from the keydown event.\n function handleKeyBinding(cm, e) {\n var name = keyName(e, true);\n if (!name) { return false }\n\n if (e.shiftKey && !cm.state.keySeq) {\n // First try to resolve full name (including 'Shift-'). Failing\n // that, see if there is a cursor-motion command (starting with\n // 'go') bound to the keyname without 'Shift-'.\n return dispatchKey(cm, \"Shift-\" + name, e, function (b) { return doHandleBinding(cm, b, true); })\n || dispatchKey(cm, name, e, function (b) {\n if (typeof b == \"string\" ? /^go[A-Z]/.test(b) : b.motion)\n { return doHandleBinding(cm, b) }\n })\n } else {\n return dispatchKey(cm, name, e, function (b) { return doHandleBinding(cm, b); })\n }\n }\n\n // Handle a key from the keypress event\n function handleCharBinding(cm, e, ch) {\n return dispatchKey(cm, \"'\" + ch + \"'\", e, function (b) { return doHandleBinding(cm, b, true); })\n }\n\n var lastStoppedKey = null;\n function onKeyDown(e) {\n var cm = this;\n if (e.target && e.target != cm.display.input.getField()) { return }\n cm.curOp.focus = activeElt(doc(cm));\n if (signalDOMEvent(cm, e)) { return }\n // IE does strange things with escape.\n if (ie && ie_version < 11 && e.keyCode == 27) { e.returnValue = false; }\n var code = e.keyCode;\n cm.display.shift = code == 16 || e.shiftKey;\n var handled = handleKeyBinding(cm, e);\n if (presto) {\n lastStoppedKey = handled ? code : null;\n // Opera has no cut event... we try to at least catch the key combo\n if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))\n { cm.replaceSelection(\"\", null, \"cut\"); }\n }\n if (gecko && !mac && !handled && code == 46 && e.shiftKey && !e.ctrlKey && document.execCommand)\n { document.execCommand(\"cut\"); }\n\n // Turn mouse into crosshair when Alt is held on Mac.\n if (code == 18 && !/\\bCodeMirror-crosshair\\b/.test(cm.display.lineDiv.className))\n { showCrossHair(cm); }\n }\n\n function showCrossHair(cm) {\n var lineDiv = cm.display.lineDiv;\n addClass(lineDiv, \"CodeMirror-crosshair\");\n\n function up(e) {\n if (e.keyCode == 18 || !e.altKey) {\n rmClass(lineDiv, \"CodeMirror-crosshair\");\n off(document, \"keyup\", up);\n off(document, \"mouseover\", up);\n }\n }\n on(document, \"keyup\", up);\n on(document, \"mouseover\", up);\n }\n\n function onKeyUp(e) {\n if (e.keyCode == 16) { this.doc.sel.shift = false; }\n signalDOMEvent(this, e);\n }\n\n function onKeyPress(e) {\n var cm = this;\n if (e.target && e.target != cm.display.input.getField()) { return }\n if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) { return }\n var keyCode = e.keyCode, charCode = e.charCode;\n if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return}\n if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) { return }\n var ch = String.fromCharCode(charCode == null ? keyCode : charCode);\n // Some browsers fire keypress events for backspace\n if (ch == \"\\x08\") { return }\n if (handleCharBinding(cm, e, ch)) { return }\n cm.display.input.onKeyPress(e);\n }\n\n var DOUBLECLICK_DELAY = 400;\n\n var PastClick = function(time, pos, button) {\n this.time = time;\n this.pos = pos;\n this.button = button;\n };\n\n PastClick.prototype.compare = function (time, pos, button) {\n return this.time + DOUBLECLICK_DELAY > time &&\n cmp(pos, this.pos) == 0 && button == this.button\n };\n\n var lastClick, lastDoubleClick;\n function clickRepeat(pos, button) {\n var now = +new Date;\n if (lastDoubleClick && lastDoubleClick.compare(now, pos, button)) {\n lastClick = lastDoubleClick = null;\n return \"triple\"\n } else if (lastClick && lastClick.compare(now, pos, button)) {\n lastDoubleClick = new PastClick(now, pos, button);\n lastClick = null;\n return \"double\"\n } else {\n lastClick = new PastClick(now, pos, button);\n lastDoubleClick = null;\n return \"single\"\n }\n }\n\n // A mouse down can be a single click, double click, triple click,\n // start of selection drag, start of text drag, new cursor\n // (ctrl-click), rectangle drag (alt-drag), or xwin\n // middle-click-paste. Or it might be a click on something we should\n // not interfere with, such as a scrollbar or widget.\n function onMouseDown(e) {\n var cm = this, display = cm.display;\n if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) { return }\n display.input.ensurePolled();\n display.shift = e.shiftKey;\n\n if (eventInWidget(display, e)) {\n if (!webkit) {\n // Briefly turn off draggability, to allow widgets to do\n // normal dragging things.\n display.scroller.draggable = false;\n setTimeout(function () { return display.scroller.draggable = true; }, 100);\n }\n return\n }\n if (clickInGutter(cm, e)) { return }\n var pos = posFromMouse(cm, e), button = e_button(e), repeat = pos ? clickRepeat(pos, button) : \"single\";\n win(cm).focus();\n\n // #3261: make sure, that we're not starting a second selection\n if (button == 1 && cm.state.selectingText)\n { cm.state.selectingText(e); }\n\n if (pos && handleMappedButton(cm, button, pos, repeat, e)) { return }\n\n if (button == 1) {\n if (pos) { leftButtonDown(cm, pos, repeat, e); }\n else if (e_target(e) == display.scroller) { e_preventDefault(e); }\n } else if (button == 2) {\n if (pos) { extendSelection(cm.doc, pos); }\n setTimeout(function () { return display.input.focus(); }, 20);\n } else if (button == 3) {\n if (captureRightClick) { cm.display.input.onContextMenu(e); }\n else { delayBlurEvent(cm); }\n }\n }\n\n function handleMappedButton(cm, button, pos, repeat, event) {\n var name = \"Click\";\n if (repeat == \"double\") { name = \"Double\" + name; }\n else if (repeat == \"triple\") { name = \"Triple\" + name; }\n name = (button == 1 ? \"Left\" : button == 2 ? \"Middle\" : \"Right\") + name;\n\n return dispatchKey(cm, addModifierNames(name, event), event, function (bound) {\n if (typeof bound == \"string\") { bound = commands[bound]; }\n if (!bound) { return false }\n var done = false;\n try {\n if (cm.isReadOnly()) { cm.state.suppressEdits = true; }\n done = bound(cm, pos) != Pass;\n } finally {\n cm.state.suppressEdits = false;\n }\n return done\n })\n }\n\n function configureMouse(cm, repeat, event) {\n var option = cm.getOption(\"configureMouse\");\n var value = option ? option(cm, repeat, event) : {};\n if (value.unit == null) {\n var rect = chromeOS ? event.shiftKey && event.metaKey : event.altKey;\n value.unit = rect ? \"rectangle\" : repeat == \"single\" ? \"char\" : repeat == \"double\" ? \"word\" : \"line\";\n }\n if (value.extend == null || cm.doc.extend) { value.extend = cm.doc.extend || event.shiftKey; }\n if (value.addNew == null) { value.addNew = mac ? event.metaKey : event.ctrlKey; }\n if (value.moveOnDrag == null) { value.moveOnDrag = !(mac ? event.altKey : event.ctrlKey); }\n return value\n }\n\n function leftButtonDown(cm, pos, repeat, event) {\n if (ie) { setTimeout(bind(ensureFocus, cm), 0); }\n else { cm.curOp.focus = activeElt(doc(cm)); }\n\n var behavior = configureMouse(cm, repeat, event);\n\n var sel = cm.doc.sel, contained;\n if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() &&\n repeat == \"single\" && (contained = sel.contains(pos)) > -1 &&\n (cmp((contained = sel.ranges[contained]).from(), pos) < 0 || pos.xRel > 0) &&\n (cmp(contained.to(), pos) > 0 || pos.xRel < 0))\n { leftButtonStartDrag(cm, event, pos, behavior); }\n else\n { leftButtonSelect(cm, event, pos, behavior); }\n }\n\n // Start a text drag. When it ends, see if any dragging actually\n // happen, and treat as a click if it didn't.\n function leftButtonStartDrag(cm, event, pos, behavior) {\n var display = cm.display, moved = false;\n var dragEnd = operation(cm, function (e) {\n if (webkit) { display.scroller.draggable = false; }\n cm.state.draggingText = false;\n if (cm.state.delayingBlurEvent) {\n if (cm.hasFocus()) { cm.state.delayingBlurEvent = false; }\n else { delayBlurEvent(cm); }\n }\n off(display.wrapper.ownerDocument, \"mouseup\", dragEnd);\n off(display.wrapper.ownerDocument, \"mousemove\", mouseMove);\n off(display.scroller, \"dragstart\", dragStart);\n off(display.scroller, \"drop\", dragEnd);\n if (!moved) {\n e_preventDefault(e);\n if (!behavior.addNew)\n { extendSelection(cm.doc, pos, null, null, behavior.extend); }\n // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)\n if ((webkit && !safari) || ie && ie_version == 9)\n { setTimeout(function () {display.wrapper.ownerDocument.body.focus({preventScroll: true}); display.input.focus();}, 20); }\n else\n { display.input.focus(); }\n }\n });\n var mouseMove = function(e2) {\n moved = moved || Math.abs(event.clientX - e2.clientX) + Math.abs(event.clientY - e2.clientY) >= 10;\n };\n var dragStart = function () { return moved = true; };\n // Let the drag handler handle this.\n if (webkit) { display.scroller.draggable = true; }\n cm.state.draggingText = dragEnd;\n dragEnd.copy = !behavior.moveOnDrag;\n on(display.wrapper.ownerDocument, \"mouseup\", dragEnd);\n on(display.wrapper.ownerDocument, \"mousemove\", mouseMove);\n on(display.scroller, \"dragstart\", dragStart);\n on(display.scroller, \"drop\", dragEnd);\n\n cm.state.delayingBlurEvent = true;\n setTimeout(function () { return display.input.focus(); }, 20);\n // IE's approach to draggable\n if (display.scroller.dragDrop) { display.scroller.dragDrop(); }\n }\n\n function rangeForUnit(cm, pos, unit) {\n if (unit == \"char\") { return new Range(pos, pos) }\n if (unit == \"word\") { return cm.findWordAt(pos) }\n if (unit == \"line\") { return new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))) }\n var result = unit(cm, pos);\n return new Range(result.from, result.to)\n }\n\n // Normal selection, as opposed to text dragging.\n function leftButtonSelect(cm, event, start, behavior) {\n if (ie) { delayBlurEvent(cm); }\n var display = cm.display, doc$1 = cm.doc;\n e_preventDefault(event);\n\n var ourRange, ourIndex, startSel = doc$1.sel, ranges = startSel.ranges;\n if (behavior.addNew && !behavior.extend) {\n ourIndex = doc$1.sel.contains(start);\n if (ourIndex > -1)\n { ourRange = ranges[ourIndex]; }\n else\n { ourRange = new Range(start, start); }\n } else {\n ourRange = doc$1.sel.primary();\n ourIndex = doc$1.sel.primIndex;\n }\n\n if (behavior.unit == \"rectangle\") {\n if (!behavior.addNew) { ourRange = new Range(start, start); }\n start = posFromMouse(cm, event, true, true);\n ourIndex = -1;\n } else {\n var range = rangeForUnit(cm, start, behavior.unit);\n if (behavior.extend)\n { ourRange = extendRange(ourRange, range.anchor, range.head, behavior.extend); }\n else\n { ourRange = range; }\n }\n\n if (!behavior.addNew) {\n ourIndex = 0;\n setSelection(doc$1, new Selection([ourRange], 0), sel_mouse);\n startSel = doc$1.sel;\n } else if (ourIndex == -1) {\n ourIndex = ranges.length;\n setSelection(doc$1, normalizeSelection(cm, ranges.concat([ourRange]), ourIndex),\n {scroll: false, origin: \"*mouse\"});\n } else if (ranges.length > 1 && ranges[ourIndex].empty() && behavior.unit == \"char\" && !behavior.extend) {\n setSelection(doc$1, normalizeSelection(cm, ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0),\n {scroll: false, origin: \"*mouse\"});\n startSel = doc$1.sel;\n } else {\n replaceOneSelection(doc$1, ourIndex, ourRange, sel_mouse);\n }\n\n var lastPos = start;\n function extendTo(pos) {\n if (cmp(lastPos, pos) == 0) { return }\n lastPos = pos;\n\n if (behavior.unit == \"rectangle\") {\n var ranges = [], tabSize = cm.options.tabSize;\n var startCol = countColumn(getLine(doc$1, start.line).text, start.ch, tabSize);\n var posCol = countColumn(getLine(doc$1, pos.line).text, pos.ch, tabSize);\n var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol);\n for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));\n line <= end; line++) {\n var text = getLine(doc$1, line).text, leftPos = findColumn(text, left, tabSize);\n if (left == right)\n { ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))); }\n else if (text.length > leftPos)\n { ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))); }\n }\n if (!ranges.length) { ranges.push(new Range(start, start)); }\n setSelection(doc$1, normalizeSelection(cm, startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),\n {origin: \"*mouse\", scroll: false});\n cm.scrollIntoView(pos);\n } else {\n var oldRange = ourRange;\n var range = rangeForUnit(cm, pos, behavior.unit);\n var anchor = oldRange.anchor, head;\n if (cmp(range.anchor, anchor) > 0) {\n head = range.head;\n anchor = minPos(oldRange.from(), range.anchor);\n } else {\n head = range.anchor;\n anchor = maxPos(oldRange.to(), range.head);\n }\n var ranges$1 = startSel.ranges.slice(0);\n ranges$1[ourIndex] = bidiSimplify(cm, new Range(clipPos(doc$1, anchor), head));\n setSelection(doc$1, normalizeSelection(cm, ranges$1, ourIndex), sel_mouse);\n }\n }\n\n var editorSize = display.wrapper.getBoundingClientRect();\n // Used to ensure timeout re-tries don't fire when another extend\n // happened in the meantime (clearTimeout isn't reliable -- at\n // least on Chrome, the timeouts still happen even when cleared,\n // if the clear happens after their scheduled firing time).\n var counter = 0;\n\n function extend(e) {\n var curCount = ++counter;\n var cur = posFromMouse(cm, e, true, behavior.unit == \"rectangle\");\n if (!cur) { return }\n if (cmp(cur, lastPos) != 0) {\n cm.curOp.focus = activeElt(doc(cm));\n extendTo(cur);\n var visible = visibleLines(display, doc$1);\n if (cur.line >= visible.to || cur.line < visible.from)\n { setTimeout(operation(cm, function () {if (counter == curCount) { extend(e); }}), 150); }\n } else {\n var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;\n if (outside) { setTimeout(operation(cm, function () {\n if (counter != curCount) { return }\n display.scroller.scrollTop += outside;\n extend(e);\n }), 50); }\n }\n }\n\n function done(e) {\n cm.state.selectingText = false;\n counter = Infinity;\n // If e is null or undefined we interpret this as someone trying\n // to explicitly cancel the selection rather than the user\n // letting go of the mouse button.\n if (e) {\n e_preventDefault(e);\n display.input.focus();\n }\n off(display.wrapper.ownerDocument, \"mousemove\", move);\n off(display.wrapper.ownerDocument, \"mouseup\", up);\n doc$1.history.lastSelOrigin = null;\n }\n\n var move = operation(cm, function (e) {\n if (e.buttons === 0 || !e_button(e)) { done(e); }\n else { extend(e); }\n });\n var up = operation(cm, done);\n cm.state.selectingText = up;\n on(display.wrapper.ownerDocument, \"mousemove\", move);\n on(display.wrapper.ownerDocument, \"mouseup\", up);\n }\n\n // Used when mouse-selecting to adjust the anchor to the proper side\n // of a bidi jump depending on the visual position of the head.\n function bidiSimplify(cm, range) {\n var anchor = range.anchor;\n var head = range.head;\n var anchorLine = getLine(cm.doc, anchor.line);\n if (cmp(anchor, head) == 0 && anchor.sticky == head.sticky) { return range }\n var order = getOrder(anchorLine);\n if (!order) { return range }\n var index = getBidiPartAt(order, anchor.ch, anchor.sticky), part = order[index];\n if (part.from != anchor.ch && part.to != anchor.ch) { return range }\n var boundary = index + ((part.from == anchor.ch) == (part.level != 1) ? 0 : 1);\n if (boundary == 0 || boundary == order.length) { return range }\n\n // Compute the relative visual position of the head compared to the\n // anchor (<0 is to the left, >0 to the right)\n var leftSide;\n if (head.line != anchor.line) {\n leftSide = (head.line - anchor.line) * (cm.doc.direction == \"ltr\" ? 1 : -1) > 0;\n } else {\n var headIndex = getBidiPartAt(order, head.ch, head.sticky);\n var dir = headIndex - index || (head.ch - anchor.ch) * (part.level == 1 ? -1 : 1);\n if (headIndex == boundary - 1 || headIndex == boundary)\n { leftSide = dir < 0; }\n else\n { leftSide = dir > 0; }\n }\n\n var usePart = order[boundary + (leftSide ? -1 : 0)];\n var from = leftSide == (usePart.level == 1);\n var ch = from ? usePart.from : usePart.to, sticky = from ? \"after\" : \"before\";\n return anchor.ch == ch && anchor.sticky == sticky ? range : new Range(new Pos(anchor.line, ch, sticky), head)\n }\n\n\n // Determines whether an event happened in the gutter, and fires the\n // handlers for the corresponding event.\n function gutterEvent(cm, e, type, prevent) {\n var mX, mY;\n if (e.touches) {\n mX = e.touches[0].clientX;\n mY = e.touches[0].clientY;\n } else {\n try { mX = e.clientX; mY = e.clientY; }\n catch(e$1) { return false }\n }\n if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) { return false }\n if (prevent) { e_preventDefault(e); }\n\n var display = cm.display;\n var lineBox = display.lineDiv.getBoundingClientRect();\n\n if (mY > lineBox.bottom || !hasHandler(cm, type)) { return e_defaultPrevented(e) }\n mY -= lineBox.top - display.viewOffset;\n\n for (var i = 0; i < cm.display.gutterSpecs.length; ++i) {\n var g = display.gutters.childNodes[i];\n if (g && g.getBoundingClientRect().right >= mX) {\n var line = lineAtHeight(cm.doc, mY);\n var gutter = cm.display.gutterSpecs[i];\n signal(cm, type, cm, line, gutter.className, e);\n return e_defaultPrevented(e)\n }\n }\n }\n\n function clickInGutter(cm, e) {\n return gutterEvent(cm, e, \"gutterClick\", true)\n }\n\n // CONTEXT MENU HANDLING\n\n // To make the context menu work, we need to briefly unhide the\n // textarea (making it as unobtrusive as possible) to let the\n // right-click take effect on it.\n function onContextMenu(cm, e) {\n if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) { return }\n if (signalDOMEvent(cm, e, \"contextmenu\")) { return }\n if (!captureRightClick) { cm.display.input.onContextMenu(e); }\n }\n\n function contextMenuInGutter(cm, e) {\n if (!hasHandler(cm, \"gutterContextMenu\")) { return false }\n return gutterEvent(cm, e, \"gutterContextMenu\", false)\n }\n\n function themeChanged(cm) {\n cm.display.wrapper.className = cm.display.wrapper.className.replace(/\\s*cm-s-\\S+/g, \"\") +\n cm.options.theme.replace(/(^|\\s)\\s*/g, \" cm-s-\");\n clearCaches(cm);\n }\n\n var Init = {toString: function(){return \"CodeMirror.Init\"}};\n\n var defaults = {};\n var optionHandlers = {};\n\n function defineOptions(CodeMirror) {\n var optionHandlers = CodeMirror.optionHandlers;\n\n function option(name, deflt, handle, notOnInit) {\n CodeMirror.defaults[name] = deflt;\n if (handle) { optionHandlers[name] =\n notOnInit ? function (cm, val, old) {if (old != Init) { handle(cm, val, old); }} : handle; }\n }\n\n CodeMirror.defineOption = option;\n\n // Passed to option handlers when there is no old value.\n CodeMirror.Init = Init;\n\n // These two are, on init, called from the constructor because they\n // have to be initialized before the editor can start at all.\n option(\"value\", \"\", function (cm, val) { return cm.setValue(val); }, true);\n option(\"mode\", null, function (cm, val) {\n cm.doc.modeOption = val;\n loadMode(cm);\n }, true);\n\n option(\"indentUnit\", 2, loadMode, true);\n option(\"indentWithTabs\", false);\n option(\"smartIndent\", true);\n option(\"tabSize\", 4, function (cm) {\n resetModeState(cm);\n clearCaches(cm);\n regChange(cm);\n }, true);\n\n option(\"lineSeparator\", null, function (cm, val) {\n cm.doc.lineSep = val;\n if (!val) { return }\n var newBreaks = [], lineNo = cm.doc.first;\n cm.doc.iter(function (line) {\n for (var pos = 0;;) {\n var found = line.text.indexOf(val, pos);\n if (found == -1) { break }\n pos = found + val.length;\n newBreaks.push(Pos(lineNo, found));\n }\n lineNo++;\n });\n for (var i = newBreaks.length - 1; i >= 0; i--)\n { replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)); }\n });\n option(\"specialChars\", /[\\u0000-\\u001f\\u007f-\\u009f\\u00ad\\u061c\\u200b\\u200e\\u200f\\u2028\\u2029\\u202d\\u202e\\u2066\\u2067\\u2069\\ufeff\\ufff9-\\ufffc]/g, function (cm, val, old) {\n cm.state.specialChars = new RegExp(val.source + (val.test(\"\\t\") ? \"\" : \"|\\t\"), \"g\");\n if (old != Init) { cm.refresh(); }\n });\n option(\"specialCharPlaceholder\", defaultSpecialCharPlaceholder, function (cm) { return cm.refresh(); }, true);\n option(\"electricChars\", true);\n option(\"inputStyle\", mobile ? \"contenteditable\" : \"textarea\", function () {\n throw new Error(\"inputStyle can not (yet) be changed in a running editor\") // FIXME\n }, true);\n option(\"spellcheck\", false, function (cm, val) { return cm.getInputField().spellcheck = val; }, true);\n option(\"autocorrect\", false, function (cm, val) { return cm.getInputField().autocorrect = val; }, true);\n option(\"autocapitalize\", false, function (cm, val) { return cm.getInputField().autocapitalize = val; }, true);\n option(\"rtlMoveVisually\", !windows);\n option(\"wholeLineUpdateBefore\", true);\n\n option(\"theme\", \"default\", function (cm) {\n themeChanged(cm);\n updateGutters(cm);\n }, true);\n option(\"keyMap\", \"default\", function (cm, val, old) {\n var next = getKeyMap(val);\n var prev = old != Init && getKeyMap(old);\n if (prev && prev.detach) { prev.detach(cm, next); }\n if (next.attach) { next.attach(cm, prev || null); }\n });\n option(\"extraKeys\", null);\n option(\"configureMouse\", null);\n\n option(\"lineWrapping\", false, wrappingChanged, true);\n option(\"gutters\", [], function (cm, val) {\n cm.display.gutterSpecs = getGutters(val, cm.options.lineNumbers);\n updateGutters(cm);\n }, true);\n option(\"fixedGutter\", true, function (cm, val) {\n cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + \"px\" : \"0\";\n cm.refresh();\n }, true);\n option(\"coverGutterNextToScrollbar\", false, function (cm) { return updateScrollbars(cm); }, true);\n option(\"scrollbarStyle\", \"native\", function (cm) {\n initScrollbars(cm);\n updateScrollbars(cm);\n cm.display.scrollbars.setScrollTop(cm.doc.scrollTop);\n cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft);\n }, true);\n option(\"lineNumbers\", false, function (cm, val) {\n cm.display.gutterSpecs = getGutters(cm.options.gutters, val);\n updateGutters(cm);\n }, true);\n option(\"firstLineNumber\", 1, updateGutters, true);\n option(\"lineNumberFormatter\", function (integer) { return integer; }, updateGutters, true);\n option(\"showCursorWhenSelecting\", false, updateSelection, true);\n\n option(\"resetSelectionOnContextMenu\", true);\n option(\"lineWiseCopyCut\", true);\n option(\"pasteLinesPerSelection\", true);\n option(\"selectionsMayTouch\", false);\n\n option(\"readOnly\", false, function (cm, val) {\n if (val == \"nocursor\") {\n onBlur(cm);\n cm.display.input.blur();\n }\n cm.display.input.readOnlyChanged(val);\n });\n\n option(\"screenReaderLabel\", null, function (cm, val) {\n val = (val === '') ? null : val;\n cm.display.input.screenReaderLabelChanged(val);\n });\n\n option(\"disableInput\", false, function (cm, val) {if (!val) { cm.display.input.reset(); }}, true);\n option(\"dragDrop\", true, dragDropChanged);\n option(\"allowDropFileTypes\", null);\n\n option(\"cursorBlinkRate\", 530);\n option(\"cursorScrollMargin\", 0);\n option(\"cursorHeight\", 1, updateSelection, true);\n option(\"singleCursorHeightPerLine\", true, updateSelection, true);\n option(\"workTime\", 100);\n option(\"workDelay\", 100);\n option(\"flattenSpans\", true, resetModeState, true);\n option(\"addModeClass\", false, resetModeState, true);\n option(\"pollInterval\", 100);\n option(\"undoDepth\", 200, function (cm, val) { return cm.doc.history.undoDepth = val; });\n option(\"historyEventDelay\", 1250);\n option(\"viewportMargin\", 10, function (cm) { return cm.refresh(); }, true);\n option(\"maxHighlightLength\", 10000, resetModeState, true);\n option(\"moveInputWithCursor\", true, function (cm, val) {\n if (!val) { cm.display.input.resetPosition(); }\n });\n\n option(\"tabindex\", null, function (cm, val) { return cm.display.input.getField().tabIndex = val || \"\"; });\n option(\"autofocus\", null);\n option(\"direction\", \"ltr\", function (cm, val) { return cm.doc.setDirection(val); }, true);\n option(\"phrases\", null);\n }\n\n function dragDropChanged(cm, value, old) {\n var wasOn = old && old != Init;\n if (!value != !wasOn) {\n var funcs = cm.display.dragFunctions;\n var toggle = value ? on : off;\n toggle(cm.display.scroller, \"dragstart\", funcs.start);\n toggle(cm.display.scroller, \"dragenter\", funcs.enter);\n toggle(cm.display.scroller, \"dragover\", funcs.over);\n toggle(cm.display.scroller, \"dragleave\", funcs.leave);\n toggle(cm.display.scroller, \"drop\", funcs.drop);\n }\n }\n\n function wrappingChanged(cm) {\n if (cm.options.lineWrapping) {\n addClass(cm.display.wrapper, \"CodeMirror-wrap\");\n cm.display.sizer.style.minWidth = \"\";\n cm.display.sizerWidth = null;\n } else {\n rmClass(cm.display.wrapper, \"CodeMirror-wrap\");\n findMaxLine(cm);\n }\n estimateLineHeights(cm);\n regChange(cm);\n clearCaches(cm);\n setTimeout(function () { return updateScrollbars(cm); }, 100);\n }\n\n // A CodeMirror instance represents an editor. This is the object\n // that user code is usually dealing with.\n\n function CodeMirror(place, options) {\n var this$1 = this;\n\n if (!(this instanceof CodeMirror)) { return new CodeMirror(place, options) }\n\n this.options = options = options ? copyObj(options) : {};\n // Determine effective options based on given values and defaults.\n copyObj(defaults, options, false);\n\n var doc = options.value;\n if (typeof doc == \"string\") { doc = new Doc(doc, options.mode, null, options.lineSeparator, options.direction); }\n else if (options.mode) { doc.modeOption = options.mode; }\n this.doc = doc;\n\n var input = new CodeMirror.inputStyles[options.inputStyle](this);\n var display = this.display = new Display(place, doc, input, options);\n display.wrapper.CodeMirror = this;\n themeChanged(this);\n if (options.lineWrapping)\n { this.display.wrapper.className += \" CodeMirror-wrap\"; }\n initScrollbars(this);\n\n this.state = {\n keyMaps: [], // stores maps added by addKeyMap\n overlays: [], // highlighting overlays, as added by addOverlay\n modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info\n overwrite: false,\n delayingBlurEvent: false,\n focused: false,\n suppressEdits: false, // used to disable editing during key handlers when in readOnly mode\n pasteIncoming: -1, cutIncoming: -1, // help recognize paste/cut edits in input.poll\n selectingText: false,\n draggingText: false,\n highlight: new Delayed(), // stores highlight worker timeout\n keySeq: null, // Unfinished key sequence\n specialChars: null\n };\n\n if (options.autofocus && !mobile) { display.input.focus(); }\n\n // Override magic textarea content restore that IE sometimes does\n // on our hidden textarea on reload\n if (ie && ie_version < 11) { setTimeout(function () { return this$1.display.input.reset(true); }, 20); }\n\n registerEventHandlers(this);\n ensureGlobalHandlers();\n\n startOperation(this);\n this.curOp.forceUpdate = true;\n attachDoc(this, doc);\n\n if ((options.autofocus && !mobile) || this.hasFocus())\n { setTimeout(function () {\n if (this$1.hasFocus() && !this$1.state.focused) { onFocus(this$1); }\n }, 20); }\n else\n { onBlur(this); }\n\n for (var opt in optionHandlers) { if (optionHandlers.hasOwnProperty(opt))\n { optionHandlers[opt](this, options[opt], Init); } }\n maybeUpdateLineNumberWidth(this);\n if (options.finishInit) { options.finishInit(this); }\n for (var i = 0; i < initHooks.length; ++i) { initHooks[i](this); }\n endOperation(this);\n // Suppress optimizelegibility in Webkit, since it breaks text\n // measuring on line wrapping boundaries.\n if (webkit && options.lineWrapping &&\n getComputedStyle(display.lineDiv).textRendering == \"optimizelegibility\")\n { display.lineDiv.style.textRendering = \"auto\"; }\n }\n\n // The default configuration options.\n CodeMirror.defaults = defaults;\n // Functions to run when options are changed.\n CodeMirror.optionHandlers = optionHandlers;\n\n // Attach the necessary event handlers when initializing the editor\n function registerEventHandlers(cm) {\n var d = cm.display;\n on(d.scroller, \"mousedown\", operation(cm, onMouseDown));\n // Older IE's will not fire a second mousedown for a double click\n if (ie && ie_version < 11)\n { on(d.scroller, \"dblclick\", operation(cm, function (e) {\n if (signalDOMEvent(cm, e)) { return }\n var pos = posFromMouse(cm, e);\n if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) { return }\n e_preventDefault(e);\n var word = cm.findWordAt(pos);\n extendSelection(cm.doc, word.anchor, word.head);\n })); }\n else\n { on(d.scroller, \"dblclick\", function (e) { return signalDOMEvent(cm, e) || e_preventDefault(e); }); }\n // Some browsers fire contextmenu *after* opening the menu, at\n // which point we can't mess with it anymore. Context menu is\n // handled in onMouseDown for these browsers.\n on(d.scroller, \"contextmenu\", function (e) { return onContextMenu(cm, e); });\n on(d.input.getField(), \"contextmenu\", function (e) {\n if (!d.scroller.contains(e.target)) { onContextMenu(cm, e); }\n });\n\n // Used to suppress mouse event handling when a touch happens\n var touchFinished, prevTouch = {end: 0};\n function finishTouch() {\n if (d.activeTouch) {\n touchFinished = setTimeout(function () { return d.activeTouch = null; }, 1000);\n prevTouch = d.activeTouch;\n prevTouch.end = +new Date;\n }\n }\n function isMouseLikeTouchEvent(e) {\n if (e.touches.length != 1) { return false }\n var touch = e.touches[0];\n return touch.radiusX <= 1 && touch.radiusY <= 1\n }\n function farAway(touch, other) {\n if (other.left == null) { return true }\n var dx = other.left - touch.left, dy = other.top - touch.top;\n return dx * dx + dy * dy > 20 * 20\n }\n on(d.scroller, \"touchstart\", function (e) {\n if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e) && !clickInGutter(cm, e)) {\n d.input.ensurePolled();\n clearTimeout(touchFinished);\n var now = +new Date;\n d.activeTouch = {start: now, moved: false,\n prev: now - prevTouch.end <= 300 ? prevTouch : null};\n if (e.touches.length == 1) {\n d.activeTouch.left = e.touches[0].pageX;\n d.activeTouch.top = e.touches[0].pageY;\n }\n }\n });\n on(d.scroller, \"touchmove\", function () {\n if (d.activeTouch) { d.activeTouch.moved = true; }\n });\n on(d.scroller, \"touchend\", function (e) {\n var touch = d.activeTouch;\n if (touch && !eventInWidget(d, e) && touch.left != null &&\n !touch.moved && new Date - touch.start < 300) {\n var pos = cm.coordsChar(d.activeTouch, \"page\"), range;\n if (!touch.prev || farAway(touch, touch.prev)) // Single tap\n { range = new Range(pos, pos); }\n else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap\n { range = cm.findWordAt(pos); }\n else // Triple tap\n { range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))); }\n cm.setSelection(range.anchor, range.head);\n cm.focus();\n e_preventDefault(e);\n }\n finishTouch();\n });\n on(d.scroller, \"touchcancel\", finishTouch);\n\n // Sync scrolling between fake scrollbars and real scrollable\n // area, ensure viewport is updated when scrolling.\n on(d.scroller, \"scroll\", function () {\n if (d.scroller.clientHeight) {\n updateScrollTop(cm, d.scroller.scrollTop);\n setScrollLeft(cm, d.scroller.scrollLeft, true);\n signal(cm, \"scroll\", cm);\n }\n });\n\n // Listen to wheel events in order to try and update the viewport on time.\n on(d.scroller, \"mousewheel\", function (e) { return onScrollWheel(cm, e); });\n on(d.scroller, \"DOMMouseScroll\", function (e) { return onScrollWheel(cm, e); });\n\n // Prevent wrapper from ever scrolling\n on(d.wrapper, \"scroll\", function () { return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });\n\n d.dragFunctions = {\n enter: function (e) {if (!signalDOMEvent(cm, e)) { e_stop(e); }},\n over: function (e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }},\n start: function (e) { return onDragStart(cm, e); },\n drop: operation(cm, onDrop),\n leave: function (e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm); }}\n };\n\n var inp = d.input.getField();\n on(inp, \"keyup\", function (e) { return onKeyUp.call(cm, e); });\n on(inp, \"keydown\", operation(cm, onKeyDown));\n on(inp, \"keypress\", operation(cm, onKeyPress));\n on(inp, \"focus\", function (e) { return onFocus(cm, e); });\n on(inp, \"blur\", function (e) { return onBlur(cm, e); });\n }\n\n var initHooks = [];\n CodeMirror.defineInitHook = function (f) { return initHooks.push(f); };\n\n // Indent the given line. The how parameter can be \"smart\",\n // \"add\"/null, \"subtract\", or \"prev\". When aggressive is false\n // (typically set to true for forced single-line indents), empty\n // lines are not indented, and places where the mode returns Pass\n // are left alone.\n function indentLine(cm, n, how, aggressive) {\n var doc = cm.doc, state;\n if (how == null) { how = \"add\"; }\n if (how == \"smart\") {\n // Fall back to \"prev\" when the mode doesn't have an indentation\n // method.\n if (!doc.mode.indent) { how = \"prev\"; }\n else { state = getContextBefore(cm, n).state; }\n }\n\n var tabSize = cm.options.tabSize;\n var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);\n if (line.stateAfter) { line.stateAfter = null; }\n var curSpaceString = line.text.match(/^\\s*/)[0], indentation;\n if (!aggressive && !/\\S/.test(line.text)) {\n indentation = 0;\n how = \"not\";\n } else if (how == \"smart\") {\n indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);\n if (indentation == Pass || indentation > 150) {\n if (!aggressive) { return }\n how = \"prev\";\n }\n }\n if (how == \"prev\") {\n if (n > doc.first) { indentation = countColumn(getLine(doc, n-1).text, null, tabSize); }\n else { indentation = 0; }\n } else if (how == \"add\") {\n indentation = curSpace + cm.options.indentUnit;\n } else if (how == \"subtract\") {\n indentation = curSpace - cm.options.indentUnit;\n } else if (typeof how == \"number\") {\n indentation = curSpace + how;\n }\n indentation = Math.max(0, indentation);\n\n var indentString = \"\", pos = 0;\n if (cm.options.indentWithTabs)\n { for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += \"\\t\";} }\n if (pos < indentation) { indentString += spaceStr(indentation - pos); }\n\n if (indentString != curSpaceString) {\n replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), \"+input\");\n line.stateAfter = null;\n return true\n } else {\n // Ensure that, if the cursor was in the whitespace at the start\n // of the line, it is moved to the end of that space.\n for (var i$1 = 0; i$1 < doc.sel.ranges.length; i$1++) {\n var range = doc.sel.ranges[i$1];\n if (range.head.line == n && range.head.ch < curSpaceString.length) {\n var pos$1 = Pos(n, curSpaceString.length);\n replaceOneSelection(doc, i$1, new Range(pos$1, pos$1));\n break\n }\n }\n }\n }\n\n // This will be set to a {lineWise: bool, text: [string]} object, so\n // that, when pasting, we know what kind of selections the copied\n // text was made out of.\n var lastCopied = null;\n\n function setLastCopied(newLastCopied) {\n lastCopied = newLastCopied;\n }\n\n function applyTextInput(cm, inserted, deleted, sel, origin) {\n var doc = cm.doc;\n cm.display.shift = false;\n if (!sel) { sel = doc.sel; }\n\n var recent = +new Date - 200;\n var paste = origin == \"paste\" || cm.state.pasteIncoming > recent;\n var textLines = splitLinesAuto(inserted), multiPaste = null;\n // When pasting N lines into N selections, insert one line per selection\n if (paste && sel.ranges.length > 1) {\n if (lastCopied && lastCopied.text.join(\"\\n\") == inserted) {\n if (sel.ranges.length % lastCopied.text.length == 0) {\n multiPaste = [];\n for (var i = 0; i < lastCopied.text.length; i++)\n { multiPaste.push(doc.splitLines(lastCopied.text[i])); }\n }\n } else if (textLines.length == sel.ranges.length && cm.options.pasteLinesPerSelection) {\n multiPaste = map(textLines, function (l) { return [l]; });\n }\n }\n\n var updateInput = cm.curOp.updateInput;\n // Normal behavior is to insert the new text into every selection\n for (var i$1 = sel.ranges.length - 1; i$1 >= 0; i$1--) {\n var range = sel.ranges[i$1];\n var from = range.from(), to = range.to();\n if (range.empty()) {\n if (deleted && deleted > 0) // Handle deletion\n { from = Pos(from.line, from.ch - deleted); }\n else if (cm.state.overwrite && !paste) // Handle overwrite\n { to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)); }\n else if (paste && lastCopied && lastCopied.lineWise && lastCopied.text.join(\"\\n\") == textLines.join(\"\\n\"))\n { from = to = Pos(from.line, 0); }\n }\n var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i$1 % multiPaste.length] : textLines,\n origin: origin || (paste ? \"paste\" : cm.state.cutIncoming > recent ? \"cut\" : \"+input\")};\n makeChange(cm.doc, changeEvent);\n signalLater(cm, \"inputRead\", cm, changeEvent);\n }\n if (inserted && !paste)\n { triggerElectric(cm, inserted); }\n\n ensureCursorVisible(cm);\n if (cm.curOp.updateInput < 2) { cm.curOp.updateInput = updateInput; }\n cm.curOp.typing = true;\n cm.state.pasteIncoming = cm.state.cutIncoming = -1;\n }\n\n function handlePaste(e, cm) {\n var pasted = e.clipboardData && e.clipboardData.getData(\"Text\");\n if (pasted) {\n e.preventDefault();\n if (!cm.isReadOnly() && !cm.options.disableInput && cm.hasFocus())\n { runInOp(cm, function () { return applyTextInput(cm, pasted, 0, null, \"paste\"); }); }\n return true\n }\n }\n\n function triggerElectric(cm, inserted) {\n // When an 'electric' character is inserted, immediately trigger a reindent\n if (!cm.options.electricChars || !cm.options.smartIndent) { return }\n var sel = cm.doc.sel;\n\n for (var i = sel.ranges.length - 1; i >= 0; i--) {\n var range = sel.ranges[i];\n if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) { continue }\n var mode = cm.getModeAt(range.head);\n var indented = false;\n if (mode.electricChars) {\n for (var j = 0; j < mode.electricChars.length; j++)\n { if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {\n indented = indentLine(cm, range.head.line, \"smart\");\n break\n } }\n } else if (mode.electricInput) {\n if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch)))\n { indented = indentLine(cm, range.head.line, \"smart\"); }\n }\n if (indented) { signalLater(cm, \"electricInput\", cm, range.head.line); }\n }\n }\n\n function copyableRanges(cm) {\n var text = [], ranges = [];\n for (var i = 0; i < cm.doc.sel.ranges.length; i++) {\n var line = cm.doc.sel.ranges[i].head.line;\n var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)};\n ranges.push(lineRange);\n text.push(cm.getRange(lineRange.anchor, lineRange.head));\n }\n return {text: text, ranges: ranges}\n }\n\n function disableBrowserMagic(field, spellcheck, autocorrect, autocapitalize) {\n field.setAttribute(\"autocorrect\", autocorrect ? \"on\" : \"off\");\n field.setAttribute(\"autocapitalize\", autocapitalize ? \"on\" : \"off\");\n field.setAttribute(\"spellcheck\", !!spellcheck);\n }\n\n function hiddenTextarea() {\n var te = elt(\"textarea\", null, null, \"position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; min-height: 1em; outline: none\");\n var div = elt(\"div\", [te], null, \"overflow: hidden; position: relative; width: 3px; height: 0px;\");\n // The textarea is kept positioned near the cursor to prevent the\n // fact that it'll be scrolled into view on input from scrolling\n // our fake cursor out of view. On webkit, when wrap=off, paste is\n // very slow. So make the area wide instead.\n if (webkit) { te.style.width = \"1000px\"; }\n else { te.setAttribute(\"wrap\", \"off\"); }\n // If border: 0; -- iOS fails to open keyboard (issue #1287)\n if (ios) { te.style.border = \"1px solid black\"; }\n return div\n }\n\n // The publicly visible API. Note that methodOp(f) means\n // 'wrap f in an operation, performed on its `this` parameter'.\n\n // This is not the complete set of editor methods. Most of the\n // methods defined on the Doc type are also injected into\n // CodeMirror.prototype, for backwards compatibility and\n // convenience.\n\n function addEditorMethods(CodeMirror) {\n var optionHandlers = CodeMirror.optionHandlers;\n\n var helpers = CodeMirror.helpers = {};\n\n CodeMirror.prototype = {\n constructor: CodeMirror,\n focus: function(){win(this).focus(); this.display.input.focus();},\n\n setOption: function(option, value) {\n var options = this.options, old = options[option];\n if (options[option] == value && option != \"mode\") { return }\n options[option] = value;\n if (optionHandlers.hasOwnProperty(option))\n { operation(this, optionHandlers[option])(this, value, old); }\n signal(this, \"optionChange\", this, option);\n },\n\n getOption: function(option) {return this.options[option]},\n getDoc: function() {return this.doc},\n\n addKeyMap: function(map, bottom) {\n this.state.keyMaps[bottom ? \"push\" : \"unshift\"](getKeyMap(map));\n },\n removeKeyMap: function(map) {\n var maps = this.state.keyMaps;\n for (var i = 0; i < maps.length; ++i)\n { if (maps[i] == map || maps[i].name == map) {\n maps.splice(i, 1);\n return true\n } }\n },\n\n addOverlay: methodOp(function(spec, options) {\n var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);\n if (mode.startState) { throw new Error(\"Overlays may not be stateful.\") }\n insertSorted(this.state.overlays,\n {mode: mode, modeSpec: spec, opaque: options && options.opaque,\n priority: (options && options.priority) || 0},\n function (overlay) { return overlay.priority; });\n this.state.modeGen++;\n regChange(this);\n }),\n removeOverlay: methodOp(function(spec) {\n var overlays = this.state.overlays;\n for (var i = 0; i < overlays.length; ++i) {\n var cur = overlays[i].modeSpec;\n if (cur == spec || typeof spec == \"string\" && cur.name == spec) {\n overlays.splice(i, 1);\n this.state.modeGen++;\n regChange(this);\n return\n }\n }\n }),\n\n indentLine: methodOp(function(n, dir, aggressive) {\n if (typeof dir != \"string\" && typeof dir != \"number\") {\n if (dir == null) { dir = this.options.smartIndent ? \"smart\" : \"prev\"; }\n else { dir = dir ? \"add\" : \"subtract\"; }\n }\n if (isLine(this.doc, n)) { indentLine(this, n, dir, aggressive); }\n }),\n indentSelection: methodOp(function(how) {\n var ranges = this.doc.sel.ranges, end = -1;\n for (var i = 0; i < ranges.length; i++) {\n var range = ranges[i];\n if (!range.empty()) {\n var from = range.from(), to = range.to();\n var start = Math.max(end, from.line);\n end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;\n for (var j = start; j < end; ++j)\n { indentLine(this, j, how); }\n var newRanges = this.doc.sel.ranges;\n if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)\n { replaceOneSelection(this.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll); }\n } else if (range.head.line > end) {\n indentLine(this, range.head.line, how, true);\n end = range.head.line;\n if (i == this.doc.sel.primIndex) { ensureCursorVisible(this); }\n }\n }\n }),\n\n // Fetch the parser token for a given character. Useful for hacks\n // that want to inspect the mode state (say, for completion).\n getTokenAt: function(pos, precise) {\n return takeToken(this, pos, precise)\n },\n\n getLineTokens: function(line, precise) {\n return takeToken(this, Pos(line), precise, true)\n },\n\n getTokenTypeAt: function(pos) {\n pos = clipPos(this.doc, pos);\n var styles = getLineStyles(this, getLine(this.doc, pos.line));\n var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;\n var type;\n if (ch == 0) { type = styles[2]; }\n else { for (;;) {\n var mid = (before + after) >> 1;\n if ((mid ? styles[mid * 2 - 1] : 0) >= ch) { after = mid; }\n else if (styles[mid * 2 + 1] < ch) { before = mid + 1; }\n else { type = styles[mid * 2 + 2]; break }\n } }\n var cut = type ? type.indexOf(\"overlay \") : -1;\n return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1)\n },\n\n getModeAt: function(pos) {\n var mode = this.doc.mode;\n if (!mode.innerMode) { return mode }\n return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode\n },\n\n getHelper: function(pos, type) {\n return this.getHelpers(pos, type)[0]\n },\n\n getHelpers: function(pos, type) {\n var found = [];\n if (!helpers.hasOwnProperty(type)) { return found }\n var help = helpers[type], mode = this.getModeAt(pos);\n if (typeof mode[type] == \"string\") {\n if (help[mode[type]]) { found.push(help[mode[type]]); }\n } else if (mode[type]) {\n for (var i = 0; i < mode[type].length; i++) {\n var val = help[mode[type][i]];\n if (val) { found.push(val); }\n }\n } else if (mode.helperType && help[mode.helperType]) {\n found.push(help[mode.helperType]);\n } else if (help[mode.name]) {\n found.push(help[mode.name]);\n }\n for (var i$1 = 0; i$1 < help._global.length; i$1++) {\n var cur = help._global[i$1];\n if (cur.pred(mode, this) && indexOf(found, cur.val) == -1)\n { found.push(cur.val); }\n }\n return found\n },\n\n getStateAfter: function(line, precise) {\n var doc = this.doc;\n line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);\n return getContextBefore(this, line + 1, precise).state\n },\n\n cursorCoords: function(start, mode) {\n var pos, range = this.doc.sel.primary();\n if (start == null) { pos = range.head; }\n else if (typeof start == \"object\") { pos = clipPos(this.doc, start); }\n else { pos = start ? range.from() : range.to(); }\n return cursorCoords(this, pos, mode || \"page\")\n },\n\n charCoords: function(pos, mode) {\n return charCoords(this, clipPos(this.doc, pos), mode || \"page\")\n },\n\n coordsChar: function(coords, mode) {\n coords = fromCoordSystem(this, coords, mode || \"page\");\n return coordsChar(this, coords.left, coords.top)\n },\n\n lineAtHeight: function(height, mode) {\n height = fromCoordSystem(this, {top: height, left: 0}, mode || \"page\").top;\n return lineAtHeight(this.doc, height + this.display.viewOffset)\n },\n heightAtLine: function(line, mode, includeWidgets) {\n var end = false, lineObj;\n if (typeof line == \"number\") {\n var last = this.doc.first + this.doc.size - 1;\n if (line < this.doc.first) { line = this.doc.first; }\n else if (line > last) { line = last; end = true; }\n lineObj = getLine(this.doc, line);\n } else {\n lineObj = line;\n }\n return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || \"page\", includeWidgets || end).top +\n (end ? this.doc.height - heightAtLine(lineObj) : 0)\n },\n\n defaultTextHeight: function() { return textHeight(this.display) },\n defaultCharWidth: function() { return charWidth(this.display) },\n\n getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo}},\n\n addWidget: function(pos, node, scroll, vert, horiz) {\n var display = this.display;\n pos = cursorCoords(this, clipPos(this.doc, pos));\n var top = pos.bottom, left = pos.left;\n node.style.position = \"absolute\";\n node.setAttribute(\"cm-ignore-events\", \"true\");\n this.display.input.setUneditable(node);\n display.sizer.appendChild(node);\n if (vert == \"over\") {\n top = pos.top;\n } else if (vert == \"above\" || vert == \"near\") {\n var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),\n hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);\n // Default to positioning above (if specified and possible); otherwise default to positioning below\n if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)\n { top = pos.top - node.offsetHeight; }\n else if (pos.bottom + node.offsetHeight <= vspace)\n { top = pos.bottom; }\n if (left + node.offsetWidth > hspace)\n { left = hspace - node.offsetWidth; }\n }\n node.style.top = top + \"px\";\n node.style.left = node.style.right = \"\";\n if (horiz == \"right\") {\n left = display.sizer.clientWidth - node.offsetWidth;\n node.style.right = \"0px\";\n } else {\n if (horiz == \"left\") { left = 0; }\n else if (horiz == \"middle\") { left = (display.sizer.clientWidth - node.offsetWidth) / 2; }\n node.style.left = left + \"px\";\n }\n if (scroll)\n { scrollIntoView(this, {left: left, top: top, right: left + node.offsetWidth, bottom: top + node.offsetHeight}); }\n },\n\n triggerOnKeyDown: methodOp(onKeyDown),\n triggerOnKeyPress: methodOp(onKeyPress),\n triggerOnKeyUp: onKeyUp,\n triggerOnMouseDown: methodOp(onMouseDown),\n\n execCommand: function(cmd) {\n if (commands.hasOwnProperty(cmd))\n { return commands[cmd].call(null, this) }\n },\n\n triggerElectric: methodOp(function(text) { triggerElectric(this, text); }),\n\n findPosH: function(from, amount, unit, visually) {\n var dir = 1;\n if (amount < 0) { dir = -1; amount = -amount; }\n var cur = clipPos(this.doc, from);\n for (var i = 0; i < amount; ++i) {\n cur = findPosH(this.doc, cur, dir, unit, visually);\n if (cur.hitSide) { break }\n }\n return cur\n },\n\n moveH: methodOp(function(dir, unit) {\n var this$1 = this;\n\n this.extendSelectionsBy(function (range) {\n if (this$1.display.shift || this$1.doc.extend || range.empty())\n { return findPosH(this$1.doc, range.head, dir, unit, this$1.options.rtlMoveVisually) }\n else\n { return dir < 0 ? range.from() : range.to() }\n }, sel_move);\n }),\n\n deleteH: methodOp(function(dir, unit) {\n var sel = this.doc.sel, doc = this.doc;\n if (sel.somethingSelected())\n { doc.replaceSelection(\"\", null, \"+delete\"); }\n else\n { deleteNearSelection(this, function (range) {\n var other = findPosH(doc, range.head, dir, unit, false);\n return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other}\n }); }\n }),\n\n findPosV: function(from, amount, unit, goalColumn) {\n var dir = 1, x = goalColumn;\n if (amount < 0) { dir = -1; amount = -amount; }\n var cur = clipPos(this.doc, from);\n for (var i = 0; i < amount; ++i) {\n var coords = cursorCoords(this, cur, \"div\");\n if (x == null) { x = coords.left; }\n else { coords.left = x; }\n cur = findPosV(this, coords, dir, unit);\n if (cur.hitSide) { break }\n }\n return cur\n },\n\n moveV: methodOp(function(dir, unit) {\n var this$1 = this;\n\n var doc = this.doc, goals = [];\n var collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected();\n doc.extendSelectionsBy(function (range) {\n if (collapse)\n { return dir < 0 ? range.from() : range.to() }\n var headPos = cursorCoords(this$1, range.head, \"div\");\n if (range.goalColumn != null) { headPos.left = range.goalColumn; }\n goals.push(headPos.left);\n var pos = findPosV(this$1, headPos, dir, unit);\n if (unit == \"page\" && range == doc.sel.primary())\n { addToScrollTop(this$1, charCoords(this$1, pos, \"div\").top - headPos.top); }\n return pos\n }, sel_move);\n if (goals.length) { for (var i = 0; i < doc.sel.ranges.length; i++)\n { doc.sel.ranges[i].goalColumn = goals[i]; } }\n }),\n\n // Find the word at the given position (as returned by coordsChar).\n findWordAt: function(pos) {\n var doc = this.doc, line = getLine(doc, pos.line).text;\n var start = pos.ch, end = pos.ch;\n if (line) {\n var helper = this.getHelper(pos, \"wordChars\");\n if ((pos.sticky == \"before\" || end == line.length) && start) { --start; } else { ++end; }\n var startChar = line.charAt(start);\n var check = isWordChar(startChar, helper)\n ? function (ch) { return isWordChar(ch, helper); }\n : /\\s/.test(startChar) ? function (ch) { return /\\s/.test(ch); }\n : function (ch) { return (!/\\s/.test(ch) && !isWordChar(ch)); };\n while (start > 0 && check(line.charAt(start - 1))) { --start; }\n while (end < line.length && check(line.charAt(end))) { ++end; }\n }\n return new Range(Pos(pos.line, start), Pos(pos.line, end))\n },\n\n toggleOverwrite: function(value) {\n if (value != null && value == this.state.overwrite) { return }\n if (this.state.overwrite = !this.state.overwrite)\n { addClass(this.display.cursorDiv, \"CodeMirror-overwrite\"); }\n else\n { rmClass(this.display.cursorDiv, \"CodeMirror-overwrite\"); }\n\n signal(this, \"overwriteToggle\", this, this.state.overwrite);\n },\n hasFocus: function() { return this.display.input.getField() == activeElt(doc(this)) },\n isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit) },\n\n scrollTo: methodOp(function (x, y) { scrollToCoords(this, x, y); }),\n getScrollInfo: function() {\n var scroller = this.display.scroller;\n return {left: scroller.scrollLeft, top: scroller.scrollTop,\n height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,\n width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,\n clientHeight: displayHeight(this), clientWidth: displayWidth(this)}\n },\n\n scrollIntoView: methodOp(function(range, margin) {\n if (range == null) {\n range = {from: this.doc.sel.primary().head, to: null};\n if (margin == null) { margin = this.options.cursorScrollMargin; }\n } else if (typeof range == \"number\") {\n range = {from: Pos(range, 0), to: null};\n } else if (range.from == null) {\n range = {from: range, to: null};\n }\n if (!range.to) { range.to = range.from; }\n range.margin = margin || 0;\n\n if (range.from.line != null) {\n scrollToRange(this, range);\n } else {\n scrollToCoordsRange(this, range.from, range.to, range.margin);\n }\n }),\n\n setSize: methodOp(function(width, height) {\n var this$1 = this;\n\n var interpret = function (val) { return typeof val == \"number\" || /^\\d+$/.test(String(val)) ? val + \"px\" : val; };\n if (width != null) { this.display.wrapper.style.width = interpret(width); }\n if (height != null) { this.display.wrapper.style.height = interpret(height); }\n if (this.options.lineWrapping) { clearLineMeasurementCache(this); }\n var lineNo = this.display.viewFrom;\n this.doc.iter(lineNo, this.display.viewTo, function (line) {\n if (line.widgets) { for (var i = 0; i < line.widgets.length; i++)\n { if (line.widgets[i].noHScroll) { regLineChange(this$1, lineNo, \"widget\"); break } } }\n ++lineNo;\n });\n this.curOp.forceUpdate = true;\n signal(this, \"refresh\", this);\n }),\n\n operation: function(f){return runInOp(this, f)},\n startOperation: function(){return startOperation(this)},\n endOperation: function(){return endOperation(this)},\n\n refresh: methodOp(function() {\n var oldHeight = this.display.cachedTextHeight;\n regChange(this);\n this.curOp.forceUpdate = true;\n clearCaches(this);\n scrollToCoords(this, this.doc.scrollLeft, this.doc.scrollTop);\n updateGutterSpace(this.display);\n if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5 || this.options.lineWrapping)\n { estimateLineHeights(this); }\n signal(this, \"refresh\", this);\n }),\n\n swapDoc: methodOp(function(doc) {\n var old = this.doc;\n old.cm = null;\n // Cancel the current text selection if any (#5821)\n if (this.state.selectingText) { this.state.selectingText(); }\n attachDoc(this, doc);\n clearCaches(this);\n this.display.input.reset();\n scrollToCoords(this, doc.scrollLeft, doc.scrollTop);\n this.curOp.forceScroll = true;\n signalLater(this, \"swapDoc\", this, old);\n return old\n }),\n\n phrase: function(phraseText) {\n var phrases = this.options.phrases;\n return phrases && Object.prototype.hasOwnProperty.call(phrases, phraseText) ? phrases[phraseText] : phraseText\n },\n\n getInputField: function(){return this.display.input.getField()},\n getWrapperElement: function(){return this.display.wrapper},\n getScrollerElement: function(){return this.display.scroller},\n getGutterElement: function(){return this.display.gutters}\n };\n eventMixin(CodeMirror);\n\n CodeMirror.registerHelper = function(type, name, value) {\n if (!helpers.hasOwnProperty(type)) { helpers[type] = CodeMirror[type] = {_global: []}; }\n helpers[type][name] = value;\n };\n CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {\n CodeMirror.registerHelper(type, name, value);\n helpers[type]._global.push({pred: predicate, val: value});\n };\n }\n\n // Used for horizontal relative motion. Dir is -1 or 1 (left or\n // right), unit can be \"codepoint\", \"char\", \"column\" (like char, but\n // doesn't cross line boundaries), \"word\" (across next word), or\n // \"group\" (to the start of next group of word or\n // non-word-non-whitespace chars). The visually param controls\n // whether, in right-to-left text, direction 1 means to move towards\n // the next index in the string, or towards the character to the right\n // of the current position. The resulting position will have a\n // hitSide=true property if it reached the end of the document.\n function findPosH(doc, pos, dir, unit, visually) {\n var oldPos = pos;\n var origDir = dir;\n var lineObj = getLine(doc, pos.line);\n var lineDir = visually && doc.direction == \"rtl\" ? -dir : dir;\n function findNextLine() {\n var l = pos.line + lineDir;\n if (l < doc.first || l >= doc.first + doc.size) { return false }\n pos = new Pos(l, pos.ch, pos.sticky);\n return lineObj = getLine(doc, l)\n }\n function moveOnce(boundToLine) {\n var next;\n if (unit == \"codepoint\") {\n var ch = lineObj.text.charCodeAt(pos.ch + (dir > 0 ? 0 : -1));\n if (isNaN(ch)) {\n next = null;\n } else {\n var astral = dir > 0 ? ch >= 0xD800 && ch < 0xDC00 : ch >= 0xDC00 && ch < 0xDFFF;\n next = new Pos(pos.line, Math.max(0, Math.min(lineObj.text.length, pos.ch + dir * (astral ? 2 : 1))), -dir);\n }\n } else if (visually) {\n next = moveVisually(doc.cm, lineObj, pos, dir);\n } else {\n next = moveLogically(lineObj, pos, dir);\n }\n if (next == null) {\n if (!boundToLine && findNextLine())\n { pos = endOfLine(visually, doc.cm, lineObj, pos.line, lineDir); }\n else\n { return false }\n } else {\n pos = next;\n }\n return true\n }\n\n if (unit == \"char\" || unit == \"codepoint\") {\n moveOnce();\n } else if (unit == \"column\") {\n moveOnce(true);\n } else if (unit == \"word\" || unit == \"group\") {\n var sawType = null, group = unit == \"group\";\n var helper = doc.cm && doc.cm.getHelper(pos, \"wordChars\");\n for (var first = true;; first = false) {\n if (dir < 0 && !moveOnce(!first)) { break }\n var cur = lineObj.text.charAt(pos.ch) || \"\\n\";\n var type = isWordChar(cur, helper) ? \"w\"\n : group && cur == \"\\n\" ? \"n\"\n : !group || /\\s/.test(cur) ? null\n : \"p\";\n if (group && !first && !type) { type = \"s\"; }\n if (sawType && sawType != type) {\n if (dir < 0) {dir = 1; moveOnce(); pos.sticky = \"after\";}\n break\n }\n\n if (type) { sawType = type; }\n if (dir > 0 && !moveOnce(!first)) { break }\n }\n }\n var result = skipAtomic(doc, pos, oldPos, origDir, true);\n if (equalCursorPos(oldPos, result)) { result.hitSide = true; }\n return result\n }\n\n // For relative vertical movement. Dir may be -1 or 1. Unit can be\n // \"page\" or \"line\". The resulting position will have a hitSide=true\n // property if it reached the end of the document.\n function findPosV(cm, pos, dir, unit) {\n var doc = cm.doc, x = pos.left, y;\n if (unit == \"page\") {\n var pageSize = Math.min(cm.display.wrapper.clientHeight, win(cm).innerHeight || doc(cm).documentElement.clientHeight);\n var moveAmount = Math.max(pageSize - .5 * textHeight(cm.display), 3);\n y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount;\n\n } else if (unit == \"line\") {\n y = dir > 0 ? pos.bottom + 3 : pos.top - 3;\n }\n var target;\n for (;;) {\n target = coordsChar(cm, x, y);\n if (!target.outside) { break }\n if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break }\n y += dir * 5;\n }\n return target\n }\n\n // CONTENTEDITABLE INPUT STYLE\n\n var ContentEditableInput = function(cm) {\n this.cm = cm;\n this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null;\n this.polling = new Delayed();\n this.composing = null;\n this.gracePeriod = false;\n this.readDOMTimeout = null;\n };\n\n ContentEditableInput.prototype.init = function (display) {\n var this$1 = this;\n\n var input = this, cm = input.cm;\n var div = input.div = display.lineDiv;\n div.contentEditable = true;\n disableBrowserMagic(div, cm.options.spellcheck, cm.options.autocorrect, cm.options.autocapitalize);\n\n function belongsToInput(e) {\n for (var t = e.target; t; t = t.parentNode) {\n if (t == div) { return true }\n if (/\\bCodeMirror-(?:line)?widget\\b/.test(t.className)) { break }\n }\n return false\n }\n\n on(div, \"paste\", function (e) {\n if (!belongsToInput(e) || signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }\n // IE doesn't fire input events, so we schedule a read for the pasted content in this way\n if (ie_version <= 11) { setTimeout(operation(cm, function () { return this$1.updateFromDOM(); }), 20); }\n });\n\n on(div, \"compositionstart\", function (e) {\n this$1.composing = {data: e.data, done: false};\n });\n on(div, \"compositionupdate\", function (e) {\n if (!this$1.composing) { this$1.composing = {data: e.data, done: false}; }\n });\n on(div, \"compositionend\", function (e) {\n if (this$1.composing) {\n if (e.data != this$1.composing.data) { this$1.readFromDOMSoon(); }\n this$1.composing.done = true;\n }\n });\n\n on(div, \"touchstart\", function () { return input.forceCompositionEnd(); });\n\n on(div, \"input\", function () {\n if (!this$1.composing) { this$1.readFromDOMSoon(); }\n });\n\n function onCopyCut(e) {\n if (!belongsToInput(e) || signalDOMEvent(cm, e)) { return }\n if (cm.somethingSelected()) {\n setLastCopied({lineWise: false, text: cm.getSelections()});\n if (e.type == \"cut\") { cm.replaceSelection(\"\", null, \"cut\"); }\n } else if (!cm.options.lineWiseCopyCut) {\n return\n } else {\n var ranges = copyableRanges(cm);\n setLastCopied({lineWise: true, text: ranges.text});\n if (e.type == \"cut\") {\n cm.operation(function () {\n cm.setSelections(ranges.ranges, 0, sel_dontScroll);\n cm.replaceSelection(\"\", null, \"cut\");\n });\n }\n }\n if (e.clipboardData) {\n e.clipboardData.clearData();\n var content = lastCopied.text.join(\"\\n\");\n // iOS exposes the clipboard API, but seems to discard content inserted into it\n e.clipboardData.setData(\"Text\", content);\n if (e.clipboardData.getData(\"Text\") == content) {\n e.preventDefault();\n return\n }\n }\n // Old-fashioned briefly-focus-a-textarea hack\n var kludge = hiddenTextarea(), te = kludge.firstChild;\n disableBrowserMagic(te);\n cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild);\n te.value = lastCopied.text.join(\"\\n\");\n var hadFocus = activeElt(div.ownerDocument);\n selectInput(te);\n setTimeout(function () {\n cm.display.lineSpace.removeChild(kludge);\n hadFocus.focus();\n if (hadFocus == div) { input.showPrimarySelection(); }\n }, 50);\n }\n on(div, \"copy\", onCopyCut);\n on(div, \"cut\", onCopyCut);\n };\n\n ContentEditableInput.prototype.screenReaderLabelChanged = function (label) {\n // Label for screenreaders, accessibility\n if(label) {\n this.div.setAttribute('aria-label', label);\n } else {\n this.div.removeAttribute('aria-label');\n }\n };\n\n ContentEditableInput.prototype.prepareSelection = function () {\n var result = prepareSelection(this.cm, false);\n result.focus = activeElt(this.div.ownerDocument) == this.div;\n return result\n };\n\n ContentEditableInput.prototype.showSelection = function (info, takeFocus) {\n if (!info || !this.cm.display.view.length) { return }\n if (info.focus || takeFocus) { this.showPrimarySelection(); }\n this.showMultipleSelections(info);\n };\n\n ContentEditableInput.prototype.getSelection = function () {\n return this.cm.display.wrapper.ownerDocument.getSelection()\n };\n\n ContentEditableInput.prototype.showPrimarySelection = function () {\n var sel = this.getSelection(), cm = this.cm, prim = cm.doc.sel.primary();\n var from = prim.from(), to = prim.to();\n\n if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) {\n sel.removeAllRanges();\n return\n }\n\n var curAnchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);\n var curFocus = domToPos(cm, sel.focusNode, sel.focusOffset);\n if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad &&\n cmp(minPos(curAnchor, curFocus), from) == 0 &&\n cmp(maxPos(curAnchor, curFocus), to) == 0)\n { return }\n\n var view = cm.display.view;\n var start = (from.line >= cm.display.viewFrom && posToDOM(cm, from)) ||\n {node: view[0].measure.map[2], offset: 0};\n var end = to.line < cm.display.viewTo && posToDOM(cm, to);\n if (!end) {\n var measure = view[view.length - 1].measure;\n var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map;\n end = {node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3]};\n }\n\n if (!start || !end) {\n sel.removeAllRanges();\n return\n }\n\n var old = sel.rangeCount && sel.getRangeAt(0), rng;\n try { rng = range(start.node, start.offset, end.offset, end.node); }\n catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible\n if (rng) {\n if (!gecko && cm.state.focused) {\n sel.collapse(start.node, start.offset);\n if (!rng.collapsed) {\n sel.removeAllRanges();\n sel.addRange(rng);\n }\n } else {\n sel.removeAllRanges();\n sel.addRange(rng);\n }\n if (old && sel.anchorNode == null) { sel.addRange(old); }\n else if (gecko) { this.startGracePeriod(); }\n }\n this.rememberSelection();\n };\n\n ContentEditableInput.prototype.startGracePeriod = function () {\n var this$1 = this;\n\n clearTimeout(this.gracePeriod);\n this.gracePeriod = setTimeout(function () {\n this$1.gracePeriod = false;\n if (this$1.selectionChanged())\n { this$1.cm.operation(function () { return this$1.cm.curOp.selectionChanged = true; }); }\n }, 20);\n };\n\n ContentEditableInput.prototype.showMultipleSelections = function (info) {\n removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors);\n removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection);\n };\n\n ContentEditableInput.prototype.rememberSelection = function () {\n var sel = this.getSelection();\n this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset;\n this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset;\n };\n\n ContentEditableInput.prototype.selectionInEditor = function () {\n var sel = this.getSelection();\n if (!sel.rangeCount) { return false }\n var node = sel.getRangeAt(0).commonAncestorContainer;\n return contains(this.div, node)\n };\n\n ContentEditableInput.prototype.focus = function () {\n if (this.cm.options.readOnly != \"nocursor\") {\n if (!this.selectionInEditor() || activeElt(this.div.ownerDocument) != this.div)\n { this.showSelection(this.prepareSelection(), true); }\n this.div.focus();\n }\n };\n ContentEditableInput.prototype.blur = function () { this.div.blur(); };\n ContentEditableInput.prototype.getField = function () { return this.div };\n\n ContentEditableInput.prototype.supportsTouch = function () { return true };\n\n ContentEditableInput.prototype.receivedFocus = function () {\n var this$1 = this;\n\n var input = this;\n if (this.selectionInEditor())\n { setTimeout(function () { return this$1.pollSelection(); }, 20); }\n else\n { runInOp(this.cm, function () { return input.cm.curOp.selectionChanged = true; }); }\n\n function poll() {\n if (input.cm.state.focused) {\n input.pollSelection();\n input.polling.set(input.cm.options.pollInterval, poll);\n }\n }\n this.polling.set(this.cm.options.pollInterval, poll);\n };\n\n ContentEditableInput.prototype.selectionChanged = function () {\n var sel = this.getSelection();\n return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||\n sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset\n };\n\n ContentEditableInput.prototype.pollSelection = function () {\n if (this.readDOMTimeout != null || this.gracePeriod || !this.selectionChanged()) { return }\n var sel = this.getSelection(), cm = this.cm;\n // On Android Chrome (version 56, at least), backspacing into an\n // uneditable block element will put the cursor in that element,\n // and then, because it's not editable, hide the virtual keyboard.\n // Because Android doesn't allow us to actually detect backspace\n // presses in a sane way, this code checks for when that happens\n // and simulates a backspace press in this case.\n if (android && chrome && this.cm.display.gutterSpecs.length && isInGutter(sel.anchorNode)) {\n this.cm.triggerOnKeyDown({type: \"keydown\", keyCode: 8, preventDefault: Math.abs});\n this.blur();\n this.focus();\n return\n }\n if (this.composing) { return }\n this.rememberSelection();\n var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);\n var head = domToPos(cm, sel.focusNode, sel.focusOffset);\n if (anchor && head) { runInOp(cm, function () {\n setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll);\n if (anchor.bad || head.bad) { cm.curOp.selectionChanged = true; }\n }); }\n };\n\n ContentEditableInput.prototype.pollContent = function () {\n if (this.readDOMTimeout != null) {\n clearTimeout(this.readDOMTimeout);\n this.readDOMTimeout = null;\n }\n\n var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary();\n var from = sel.from(), to = sel.to();\n if (from.ch == 0 && from.line > cm.firstLine())\n { from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length); }\n if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine())\n { to = Pos(to.line + 1, 0); }\n if (from.line < display.viewFrom || to.line > display.viewTo - 1) { return false }\n\n var fromIndex, fromLine, fromNode;\n if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {\n fromLine = lineNo(display.view[0].line);\n fromNode = display.view[0].node;\n } else {\n fromLine = lineNo(display.view[fromIndex].line);\n fromNode = display.view[fromIndex - 1].node.nextSibling;\n }\n var toIndex = findViewIndex(cm, to.line);\n var toLine, toNode;\n if (toIndex == display.view.length - 1) {\n toLine = display.viewTo - 1;\n toNode = display.lineDiv.lastChild;\n } else {\n toLine = lineNo(display.view[toIndex + 1].line) - 1;\n toNode = display.view[toIndex + 1].node.previousSibling;\n }\n\n if (!fromNode) { return false }\n var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine));\n var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length));\n while (newText.length > 1 && oldText.length > 1) {\n if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; }\n else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; }\n else { break }\n }\n\n var cutFront = 0, cutEnd = 0;\n var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length);\n while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront))\n { ++cutFront; }\n var newBot = lst(newText), oldBot = lst(oldText);\n var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0),\n oldBot.length - (oldText.length == 1 ? cutFront : 0));\n while (cutEnd < maxCutEnd &&\n newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))\n { ++cutEnd; }\n // Try to move start of change to start of selection if ambiguous\n if (newText.length == 1 && oldText.length == 1 && fromLine == from.line) {\n while (cutFront && cutFront > from.ch &&\n newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) {\n cutFront--;\n cutEnd++;\n }\n }\n\n newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\\u200b+/, \"\");\n newText[0] = newText[0].slice(cutFront).replace(/\\u200b+$/, \"\");\n\n var chFrom = Pos(fromLine, cutFront);\n var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0);\n if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {\n replaceRange(cm.doc, newText, chFrom, chTo, \"+input\");\n return true\n }\n };\n\n ContentEditableInput.prototype.ensurePolled = function () {\n this.forceCompositionEnd();\n };\n ContentEditableInput.prototype.reset = function () {\n this.forceCompositionEnd();\n };\n ContentEditableInput.prototype.forceCompositionEnd = function () {\n if (!this.composing) { return }\n clearTimeout(this.readDOMTimeout);\n this.composing = null;\n this.updateFromDOM();\n this.div.blur();\n this.div.focus();\n };\n ContentEditableInput.prototype.readFromDOMSoon = function () {\n var this$1 = this;\n\n if (this.readDOMTimeout != null) { return }\n this.readDOMTimeout = setTimeout(function () {\n this$1.readDOMTimeout = null;\n if (this$1.composing) {\n if (this$1.composing.done) { this$1.composing = null; }\n else { return }\n }\n this$1.updateFromDOM();\n }, 80);\n };\n\n ContentEditableInput.prototype.updateFromDOM = function () {\n var this$1 = this;\n\n if (this.cm.isReadOnly() || !this.pollContent())\n { runInOp(this.cm, function () { return regChange(this$1.cm); }); }\n };\n\n ContentEditableInput.prototype.setUneditable = function (node) {\n node.contentEditable = \"false\";\n };\n\n ContentEditableInput.prototype.onKeyPress = function (e) {\n if (e.charCode == 0 || this.composing) { return }\n e.preventDefault();\n if (!this.cm.isReadOnly())\n { operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0); }\n };\n\n ContentEditableInput.prototype.readOnlyChanged = function (val) {\n this.div.contentEditable = String(val != \"nocursor\");\n };\n\n ContentEditableInput.prototype.onContextMenu = function () {};\n ContentEditableInput.prototype.resetPosition = function () {};\n\n ContentEditableInput.prototype.needsContentAttribute = true;\n\n function posToDOM(cm, pos) {\n var view = findViewForLine(cm, pos.line);\n if (!view || view.hidden) { return null }\n var line = getLine(cm.doc, pos.line);\n var info = mapFromLineView(view, line, pos.line);\n\n var order = getOrder(line, cm.doc.direction), side = \"left\";\n if (order) {\n var partPos = getBidiPartAt(order, pos.ch);\n side = partPos % 2 ? \"right\" : \"left\";\n }\n var result = nodeAndOffsetInLineMap(info.map, pos.ch, side);\n result.offset = result.collapse == \"right\" ? result.end : result.start;\n return result\n }\n\n function isInGutter(node) {\n for (var scan = node; scan; scan = scan.parentNode)\n { if (/CodeMirror-gutter-wrapper/.test(scan.className)) { return true } }\n return false\n }\n\n function badPos(pos, bad) { if (bad) { pos.bad = true; } return pos }\n\n function domTextBetween(cm, from, to, fromLine, toLine) {\n var text = \"\", closing = false, lineSep = cm.doc.lineSeparator(), extraLinebreak = false;\n function recognizeMarker(id) { return function (marker) { return marker.id == id; } }\n function close() {\n if (closing) {\n text += lineSep;\n if (extraLinebreak) { text += lineSep; }\n closing = extraLinebreak = false;\n }\n }\n function addText(str) {\n if (str) {\n close();\n text += str;\n }\n }\n function walk(node) {\n if (node.nodeType == 1) {\n var cmText = node.getAttribute(\"cm-text\");\n if (cmText) {\n addText(cmText);\n return\n }\n var markerID = node.getAttribute(\"cm-marker\"), range;\n if (markerID) {\n var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID));\n if (found.length && (range = found[0].find(0)))\n { addText(getBetween(cm.doc, range.from, range.to).join(lineSep)); }\n return\n }\n if (node.getAttribute(\"contenteditable\") == \"false\") { return }\n var isBlock = /^(pre|div|p|li|table|br)$/i.test(node.nodeName);\n if (!/^br$/i.test(node.nodeName) && node.textContent.length == 0) { return }\n\n if (isBlock) { close(); }\n for (var i = 0; i < node.childNodes.length; i++)\n { walk(node.childNodes[i]); }\n\n if (/^(pre|p)$/i.test(node.nodeName)) { extraLinebreak = true; }\n if (isBlock) { closing = true; }\n } else if (node.nodeType == 3) {\n addText(node.nodeValue.replace(/\\u200b/g, \"\").replace(/\\u00a0/g, \" \"));\n }\n }\n for (;;) {\n walk(from);\n if (from == to) { break }\n from = from.nextSibling;\n extraLinebreak = false;\n }\n return text\n }\n\n function domToPos(cm, node, offset) {\n var lineNode;\n if (node == cm.display.lineDiv) {\n lineNode = cm.display.lineDiv.childNodes[offset];\n if (!lineNode) { return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true) }\n node = null; offset = 0;\n } else {\n for (lineNode = node;; lineNode = lineNode.parentNode) {\n if (!lineNode || lineNode == cm.display.lineDiv) { return null }\n if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) { break }\n }\n }\n for (var i = 0; i < cm.display.view.length; i++) {\n var lineView = cm.display.view[i];\n if (lineView.node == lineNode)\n { return locateNodeInLineView(lineView, node, offset) }\n }\n }\n\n function locateNodeInLineView(lineView, node, offset) {\n var wrapper = lineView.text.firstChild, bad = false;\n if (!node || !contains(wrapper, node)) { return badPos(Pos(lineNo(lineView.line), 0), true) }\n if (node == wrapper) {\n bad = true;\n node = wrapper.childNodes[offset];\n offset = 0;\n if (!node) {\n var line = lineView.rest ? lst(lineView.rest) : lineView.line;\n return badPos(Pos(lineNo(line), line.text.length), bad)\n }\n }\n\n var textNode = node.nodeType == 3 ? node : null, topNode = node;\n if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {\n textNode = node.firstChild;\n if (offset) { offset = textNode.nodeValue.length; }\n }\n while (topNode.parentNode != wrapper) { topNode = topNode.parentNode; }\n var measure = lineView.measure, maps = measure.maps;\n\n function find(textNode, topNode, offset) {\n for (var i = -1; i < (maps ? maps.length : 0); i++) {\n var map = i < 0 ? measure.map : maps[i];\n for (var j = 0; j < map.length; j += 3) {\n var curNode = map[j + 2];\n if (curNode == textNode || curNode == topNode) {\n var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]);\n var ch = map[j] + offset;\n if (offset < 0 || curNode != textNode) { ch = map[j + (offset ? 1 : 0)]; }\n return Pos(line, ch)\n }\n }\n }\n }\n var found = find(textNode, topNode, offset);\n if (found) { return badPos(found, bad) }\n\n // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems\n for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {\n found = find(after, after.firstChild, 0);\n if (found)\n { return badPos(Pos(found.line, found.ch - dist), bad) }\n else\n { dist += after.textContent.length; }\n }\n for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) {\n found = find(before, before.firstChild, -1);\n if (found)\n { return badPos(Pos(found.line, found.ch + dist$1), bad) }\n else\n { dist$1 += before.textContent.length; }\n }\n }\n\n // TEXTAREA INPUT STYLE\n\n var TextareaInput = function(cm) {\n this.cm = cm;\n // See input.poll and input.reset\n this.prevInput = \"\";\n\n // Flag that indicates whether we expect input to appear real soon\n // now (after some event like 'keypress' or 'input') and are\n // polling intensively.\n this.pollingFast = false;\n // Self-resetting timeout for the poller\n this.polling = new Delayed();\n // Used to work around IE issue with selection being forgotten when focus moves away from textarea\n this.hasSelection = false;\n this.composing = null;\n this.resetting = false;\n };\n\n TextareaInput.prototype.init = function (display) {\n var this$1 = this;\n\n var input = this, cm = this.cm;\n this.createField(display);\n var te = this.textarea;\n\n display.wrapper.insertBefore(this.wrapper, display.wrapper.firstChild);\n\n // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)\n if (ios) { te.style.width = \"0px\"; }\n\n on(te, \"input\", function () {\n if (ie && ie_version >= 9 && this$1.hasSelection) { this$1.hasSelection = null; }\n input.poll();\n });\n\n on(te, \"paste\", function (e) {\n if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }\n\n cm.state.pasteIncoming = +new Date;\n input.fastPoll();\n });\n\n function prepareCopyCut(e) {\n if (signalDOMEvent(cm, e)) { return }\n if (cm.somethingSelected()) {\n setLastCopied({lineWise: false, text: cm.getSelections()});\n } else if (!cm.options.lineWiseCopyCut) {\n return\n } else {\n var ranges = copyableRanges(cm);\n setLastCopied({lineWise: true, text: ranges.text});\n if (e.type == \"cut\") {\n cm.setSelections(ranges.ranges, null, sel_dontScroll);\n } else {\n input.prevInput = \"\";\n te.value = ranges.text.join(\"\\n\");\n selectInput(te);\n }\n }\n if (e.type == \"cut\") { cm.state.cutIncoming = +new Date; }\n }\n on(te, \"cut\", prepareCopyCut);\n on(te, \"copy\", prepareCopyCut);\n\n on(display.scroller, \"paste\", function (e) {\n if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { return }\n if (!te.dispatchEvent) {\n cm.state.pasteIncoming = +new Date;\n input.focus();\n return\n }\n\n // Pass the `paste` event to the textarea so it's handled by its event listener.\n var event = new Event(\"paste\");\n event.clipboardData = e.clipboardData;\n te.dispatchEvent(event);\n });\n\n // Prevent normal selection in the editor (we handle our own)\n on(display.lineSpace, \"selectstart\", function (e) {\n if (!eventInWidget(display, e)) { e_preventDefault(e); }\n });\n\n on(te, \"compositionstart\", function () {\n var start = cm.getCursor(\"from\");\n if (input.composing) { input.composing.range.clear(); }\n input.composing = {\n start: start,\n range: cm.markText(start, cm.getCursor(\"to\"), {className: \"CodeMirror-composing\"})\n };\n });\n on(te, \"compositionend\", function () {\n if (input.composing) {\n input.poll();\n input.composing.range.clear();\n input.composing = null;\n }\n });\n };\n\n TextareaInput.prototype.createField = function (_display) {\n // Wraps and hides input textarea\n this.wrapper = hiddenTextarea();\n // The semihidden textarea that is focused when the editor is\n // focused, and receives input.\n this.textarea = this.wrapper.firstChild;\n var opts = this.cm.options;\n disableBrowserMagic(this.textarea, opts.spellcheck, opts.autocorrect, opts.autocapitalize);\n };\n\n TextareaInput.prototype.screenReaderLabelChanged = function (label) {\n // Label for screenreaders, accessibility\n if(label) {\n this.textarea.setAttribute('aria-label', label);\n } else {\n this.textarea.removeAttribute('aria-label');\n }\n };\n\n TextareaInput.prototype.prepareSelection = function () {\n // Redraw the selection and/or cursor\n var cm = this.cm, display = cm.display, doc = cm.doc;\n var result = prepareSelection(cm);\n\n // Move the hidden textarea near the cursor to prevent scrolling artifacts\n if (cm.options.moveInputWithCursor) {\n var headPos = cursorCoords(cm, doc.sel.primary().head, \"div\");\n var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();\n result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,\n headPos.top + lineOff.top - wrapOff.top));\n result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,\n headPos.left + lineOff.left - wrapOff.left));\n }\n\n return result\n };\n\n TextareaInput.prototype.showSelection = function (drawn) {\n var cm = this.cm, display = cm.display;\n removeChildrenAndAdd(display.cursorDiv, drawn.cursors);\n removeChildrenAndAdd(display.selectionDiv, drawn.selection);\n if (drawn.teTop != null) {\n this.wrapper.style.top = drawn.teTop + \"px\";\n this.wrapper.style.left = drawn.teLeft + \"px\";\n }\n };\n\n // Reset the input to correspond to the selection (or to be empty,\n // when not typing and nothing is selected)\n TextareaInput.prototype.reset = function (typing) {\n if (this.contextMenuPending || this.composing && typing) { return }\n var cm = this.cm;\n this.resetting = true;\n if (cm.somethingSelected()) {\n this.prevInput = \"\";\n var content = cm.getSelection();\n this.textarea.value = content;\n if (cm.state.focused) { selectInput(this.textarea); }\n if (ie && ie_version >= 9) { this.hasSelection = content; }\n } else if (!typing) {\n this.prevInput = this.textarea.value = \"\";\n if (ie && ie_version >= 9) { this.hasSelection = null; }\n }\n this.resetting = false;\n };\n\n TextareaInput.prototype.getField = function () { return this.textarea };\n\n TextareaInput.prototype.supportsTouch = function () { return false };\n\n TextareaInput.prototype.focus = function () {\n if (this.cm.options.readOnly != \"nocursor\" && (!mobile || activeElt(this.textarea.ownerDocument) != this.textarea)) {\n try { this.textarea.focus(); }\n catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM\n }\n };\n\n TextareaInput.prototype.blur = function () { this.textarea.blur(); };\n\n TextareaInput.prototype.resetPosition = function () {\n this.wrapper.style.top = this.wrapper.style.left = 0;\n };\n\n TextareaInput.prototype.receivedFocus = function () { this.slowPoll(); };\n\n // Poll for input changes, using the normal rate of polling. This\n // runs as long as the editor is focused.\n TextareaInput.prototype.slowPoll = function () {\n var this$1 = this;\n\n if (this.pollingFast) { return }\n this.polling.set(this.cm.options.pollInterval, function () {\n this$1.poll();\n if (this$1.cm.state.focused) { this$1.slowPoll(); }\n });\n };\n\n // When an event has just come in that is likely to add or change\n // something in the input textarea, we poll faster, to ensure that\n // the change appears on the screen quickly.\n TextareaInput.prototype.fastPoll = function () {\n var missed = false, input = this;\n input.pollingFast = true;\n function p() {\n var changed = input.poll();\n if (!changed && !missed) {missed = true; input.polling.set(60, p);}\n else {input.pollingFast = false; input.slowPoll();}\n }\n input.polling.set(20, p);\n };\n\n // Read input from the textarea, and update the document to match.\n // When something is selected, it is present in the textarea, and\n // selected (unless it is huge, in which case a placeholder is\n // used). When nothing is selected, the cursor sits after previously\n // seen text (can be empty), which is stored in prevInput (we must\n // not reset the textarea when typing, because that breaks IME).\n TextareaInput.prototype.poll = function () {\n var this$1 = this;\n\n var cm = this.cm, input = this.textarea, prevInput = this.prevInput;\n // Since this is called a *lot*, try to bail out as cheaply as\n // possible when it is clear that nothing happened. hasSelection\n // will be the case when there is a lot of text in the textarea,\n // in which case reading its value would be expensive.\n if (this.contextMenuPending || this.resetting || !cm.state.focused ||\n (hasSelection(input) && !prevInput && !this.composing) ||\n cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq)\n { return false }\n\n var text = input.value;\n // If nothing changed, bail.\n if (text == prevInput && !cm.somethingSelected()) { return false }\n // Work around nonsensical selection resetting in IE9/10, and\n // inexplicable appearance of private area unicode characters on\n // some key combos in Mac (#2689).\n if (ie && ie_version >= 9 && this.hasSelection === text ||\n mac && /[\\uf700-\\uf7ff]/.test(text)) {\n cm.display.input.reset();\n return false\n }\n\n if (cm.doc.sel == cm.display.selForContextMenu) {\n var first = text.charCodeAt(0);\n if (first == 0x200b && !prevInput) { prevInput = \"\\u200b\"; }\n if (first == 0x21da) { this.reset(); return this.cm.execCommand(\"undo\") }\n }\n // Find the part of the input that is actually new\n var same = 0, l = Math.min(prevInput.length, text.length);\n while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) { ++same; }\n\n runInOp(cm, function () {\n applyTextInput(cm, text.slice(same), prevInput.length - same,\n null, this$1.composing ? \"*compose\" : null);\n\n // Don't leave long text in the textarea, since it makes further polling slow\n if (text.length > 1000 || text.indexOf(\"\\n\") > -1) { input.value = this$1.prevInput = \"\"; }\n else { this$1.prevInput = text; }\n\n if (this$1.composing) {\n this$1.composing.range.clear();\n this$1.composing.range = cm.markText(this$1.composing.start, cm.getCursor(\"to\"),\n {className: \"CodeMirror-composing\"});\n }\n });\n return true\n };\n\n TextareaInput.prototype.ensurePolled = function () {\n if (this.pollingFast && this.poll()) { this.pollingFast = false; }\n };\n\n TextareaInput.prototype.onKeyPress = function () {\n if (ie && ie_version >= 9) { this.hasSelection = null; }\n this.fastPoll();\n };\n\n TextareaInput.prototype.onContextMenu = function (e) {\n var input = this, cm = input.cm, display = cm.display, te = input.textarea;\n if (input.contextMenuPending) { input.contextMenuPending(); }\n var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;\n if (!pos || presto) { return } // Opera is difficult.\n\n // Reset the current text selection only if the click is done outside of the selection\n // and 'resetSelectionOnContextMenu' option is true.\n var reset = cm.options.resetSelectionOnContextMenu;\n if (reset && cm.doc.sel.contains(pos) == -1)\n { operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll); }\n\n var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText;\n var wrapperBox = input.wrapper.offsetParent.getBoundingClientRect();\n input.wrapper.style.cssText = \"position: static\";\n te.style.cssText = \"position: absolute; width: 30px; height: 30px;\\n top: \" + (e.clientY - wrapperBox.top - 5) + \"px; left: \" + (e.clientX - wrapperBox.left - 5) + \"px;\\n z-index: 1000; background: \" + (ie ? \"rgba(255, 255, 255, .05)\" : \"transparent\") + \";\\n outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);\";\n var oldScrollY;\n if (webkit) { oldScrollY = te.ownerDocument.defaultView.scrollY; } // Work around Chrome issue (#2712)\n display.input.focus();\n if (webkit) { te.ownerDocument.defaultView.scrollTo(null, oldScrollY); }\n display.input.reset();\n // Adds \"Select all\" to context menu in FF\n if (!cm.somethingSelected()) { te.value = input.prevInput = \" \"; }\n input.contextMenuPending = rehide;\n display.selForContextMenu = cm.doc.sel;\n clearTimeout(display.detectingSelectAll);\n\n // Select-all will be greyed out if there's nothing to select, so\n // this adds a zero-width space so that we can later check whether\n // it got selected.\n function prepareSelectAllHack() {\n if (te.selectionStart != null) {\n var selected = cm.somethingSelected();\n var extval = \"\\u200b\" + (selected ? te.value : \"\");\n te.value = \"\\u21da\"; // Used to catch context-menu undo\n te.value = extval;\n input.prevInput = selected ? \"\" : \"\\u200b\";\n te.selectionStart = 1; te.selectionEnd = extval.length;\n // Re-set this, in case some other handler touched the\n // selection in the meantime.\n display.selForContextMenu = cm.doc.sel;\n }\n }\n function rehide() {\n if (input.contextMenuPending != rehide) { return }\n input.contextMenuPending = false;\n input.wrapper.style.cssText = oldWrapperCSS;\n te.style.cssText = oldCSS;\n if (ie && ie_version < 9) { display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos); }\n\n // Try to detect the user choosing select-all\n if (te.selectionStart != null) {\n if (!ie || (ie && ie_version < 9)) { prepareSelectAllHack(); }\n var i = 0, poll = function () {\n if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 &&\n te.selectionEnd > 0 && input.prevInput == \"\\u200b\") {\n operation(cm, selectAll)(cm);\n } else if (i++ < 10) {\n display.detectingSelectAll = setTimeout(poll, 500);\n } else {\n display.selForContextMenu = null;\n display.input.reset();\n }\n };\n display.detectingSelectAll = setTimeout(poll, 200);\n }\n }\n\n if (ie && ie_version >= 9) { prepareSelectAllHack(); }\n if (captureRightClick) {\n e_stop(e);\n var mouseup = function () {\n off(window, \"mouseup\", mouseup);\n setTimeout(rehide, 20);\n };\n on(window, \"mouseup\", mouseup);\n } else {\n setTimeout(rehide, 50);\n }\n };\n\n TextareaInput.prototype.readOnlyChanged = function (val) {\n if (!val) { this.reset(); }\n this.textarea.disabled = val == \"nocursor\";\n this.textarea.readOnly = !!val;\n };\n\n TextareaInput.prototype.setUneditable = function () {};\n\n TextareaInput.prototype.needsContentAttribute = false;\n\n function fromTextArea(textarea, options) {\n options = options ? copyObj(options) : {};\n options.value = textarea.value;\n if (!options.tabindex && textarea.tabIndex)\n { options.tabindex = textarea.tabIndex; }\n if (!options.placeholder && textarea.placeholder)\n { options.placeholder = textarea.placeholder; }\n // Set autofocus to true if this textarea is focused, or if it has\n // autofocus and no other element is focused.\n if (options.autofocus == null) {\n var hasFocus = activeElt(textarea.ownerDocument);\n options.autofocus = hasFocus == textarea ||\n textarea.getAttribute(\"autofocus\") != null && hasFocus == document.body;\n }\n\n function save() {textarea.value = cm.getValue();}\n\n var realSubmit;\n if (textarea.form) {\n on(textarea.form, \"submit\", save);\n // Deplorable hack to make the submit method do the right thing.\n if (!options.leaveSubmitMethodAlone) {\n var form = textarea.form;\n realSubmit = form.submit;\n try {\n var wrappedSubmit = form.submit = function () {\n save();\n form.submit = realSubmit;\n form.submit();\n form.submit = wrappedSubmit;\n };\n } catch(e) {}\n }\n }\n\n options.finishInit = function (cm) {\n cm.save = save;\n cm.getTextArea = function () { return textarea; };\n cm.toTextArea = function () {\n cm.toTextArea = isNaN; // Prevent this from being ran twice\n save();\n textarea.parentNode.removeChild(cm.getWrapperElement());\n textarea.style.display = \"\";\n if (textarea.form) {\n off(textarea.form, \"submit\", save);\n if (!options.leaveSubmitMethodAlone && typeof textarea.form.submit == \"function\")\n { textarea.form.submit = realSubmit; }\n }\n };\n };\n\n textarea.style.display = \"none\";\n var cm = CodeMirror(function (node) { return textarea.parentNode.insertBefore(node, textarea.nextSibling); },\n options);\n return cm\n }\n\n function addLegacyProps(CodeMirror) {\n CodeMirror.off = off;\n CodeMirror.on = on;\n CodeMirror.wheelEventPixels = wheelEventPixels;\n CodeMirror.Doc = Doc;\n CodeMirror.splitLines = splitLinesAuto;\n CodeMirror.countColumn = countColumn;\n CodeMirror.findColumn = findColumn;\n CodeMirror.isWordChar = isWordCharBasic;\n CodeMirror.Pass = Pass;\n CodeMirror.signal = signal;\n CodeMirror.Line = Line;\n CodeMirror.changeEnd = changeEnd;\n CodeMirror.scrollbarModel = scrollbarModel;\n CodeMirror.Pos = Pos;\n CodeMirror.cmpPos = cmp;\n CodeMirror.modes = modes;\n CodeMirror.mimeModes = mimeModes;\n CodeMirror.resolveMode = resolveMode;\n CodeMirror.getMode = getMode;\n CodeMirror.modeExtensions = modeExtensions;\n CodeMirror.extendMode = extendMode;\n CodeMirror.copyState = copyState;\n CodeMirror.startState = startState;\n CodeMirror.innerMode = innerMode;\n CodeMirror.commands = commands;\n CodeMirror.keyMap = keyMap;\n CodeMirror.keyName = keyName;\n CodeMirror.isModifierKey = isModifierKey;\n CodeMirror.lookupKey = lookupKey;\n CodeMirror.normalizeKeyMap = normalizeKeyMap;\n CodeMirror.StringStream = StringStream;\n CodeMirror.SharedTextMarker = SharedTextMarker;\n CodeMirror.TextMarker = TextMarker;\n CodeMirror.LineWidget = LineWidget;\n CodeMirror.e_preventDefault = e_preventDefault;\n CodeMirror.e_stopPropagation = e_stopPropagation;\n CodeMirror.e_stop = e_stop;\n CodeMirror.addClass = addClass;\n CodeMirror.contains = contains;\n CodeMirror.rmClass = rmClass;\n CodeMirror.keyNames = keyNames;\n }\n\n // EDITOR CONSTRUCTOR\n\n defineOptions(CodeMirror);\n\n addEditorMethods(CodeMirror);\n\n // Set up methods on CodeMirror's prototype to redirect to the editor's document.\n var dontDelegate = \"iter insert remove copy getEditor constructor\".split(\" \");\n for (var prop in Doc.prototype) { if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)\n { CodeMirror.prototype[prop] = (function(method) {\n return function() {return method.apply(this.doc, arguments)}\n })(Doc.prototype[prop]); } }\n\n eventMixin(Doc);\n CodeMirror.inputStyles = {\"textarea\": TextareaInput, \"contenteditable\": ContentEditableInput};\n\n // Extra arguments are stored as the mode's dependencies, which is\n // used by (legacy) mechanisms like loadmode.js to automatically\n // load a mode. (Preferred mechanism is the require/define calls.)\n CodeMirror.defineMode = function(name/*, mode, …*/) {\n if (!CodeMirror.defaults.mode && name != \"null\") { CodeMirror.defaults.mode = name; }\n defineMode.apply(this, arguments);\n };\n\n CodeMirror.defineMIME = defineMIME;\n\n // Minimal default mode.\n CodeMirror.defineMode(\"null\", function () { return ({token: function (stream) { return stream.skipToEnd(); }}); });\n CodeMirror.defineMIME(\"text/plain\", \"null\");\n\n // EXTENSIONS\n\n CodeMirror.defineExtension = function (name, func) {\n CodeMirror.prototype[name] = func;\n };\n CodeMirror.defineDocExtension = function (name, func) {\n Doc.prototype[name] = func;\n };\n\n CodeMirror.fromTextArea = fromTextArea;\n\n addLegacyProps(CodeMirror);\n\n CodeMirror.version = \"5.65.12\";\n\n return CodeMirror;\n\n})));\n","// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/5/LICENSE\n\n// declare global: diff_match_patch, DIFF_INSERT, DIFF_DELETE, DIFF_EQUAL\n\n(function(mod) {\n if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n mod(require(\"../../lib/codemirror\")); // Note non-packaged dependency diff_match_patch\n else if (typeof define == \"function\" && define.amd) // AMD\n define([\"../../lib/codemirror\", \"diff_match_patch\"], mod);\n else // Plain browser env\n mod(CodeMirror);\n})(function(CodeMirror) {\n \"use strict\";\n var Pos = CodeMirror.Pos;\n var svgNS = \"http://www.w3.org/2000/svg\";\n\n function DiffView(mv, type) {\n this.mv = mv;\n this.type = type;\n this.classes = type == \"left\"\n ? {chunk: \"CodeMirror-merge-l-chunk\",\n start: \"CodeMirror-merge-l-chunk-start\",\n end: \"CodeMirror-merge-l-chunk-end\",\n insert: \"CodeMirror-merge-l-inserted\",\n del: \"CodeMirror-merge-l-deleted\",\n connect: \"CodeMirror-merge-l-connect\"}\n : {chunk: \"CodeMirror-merge-r-chunk\",\n start: \"CodeMirror-merge-r-chunk-start\",\n end: \"CodeMirror-merge-r-chunk-end\",\n insert: \"CodeMirror-merge-r-inserted\",\n del: \"CodeMirror-merge-r-deleted\",\n connect: \"CodeMirror-merge-r-connect\"};\n }\n\n DiffView.prototype = {\n constructor: DiffView,\n init: function(pane, orig, options) {\n this.edit = this.mv.edit;\n ;(this.edit.state.diffViews || (this.edit.state.diffViews = [])).push(this);\n this.orig = CodeMirror(pane, copyObj({value: orig, readOnly: !this.mv.options.allowEditingOriginals}, copyObj(options)));\n if (this.mv.options.connect == \"align\") {\n if (!this.edit.state.trackAlignable) this.edit.state.trackAlignable = new TrackAlignable(this.edit)\n this.orig.state.trackAlignable = new TrackAlignable(this.orig)\n }\n this.lockButton.title = this.edit.phrase(\"Toggle locked scrolling\");\n this.lockButton.setAttribute(\"aria-label\", this.lockButton.title);\n\n this.orig.state.diffViews = [this];\n var classLocation = options.chunkClassLocation || \"background\";\n if (Object.prototype.toString.call(classLocation) != \"[object Array]\") classLocation = [classLocation]\n this.classes.classLocation = classLocation\n\n this.diff = getDiff(asString(orig), asString(options.value), this.mv.options.ignoreWhitespace);\n this.chunks = getChunks(this.diff);\n this.diffOutOfDate = this.dealigned = false;\n this.needsScrollSync = null\n\n this.showDifferences = options.showDifferences !== false;\n },\n registerEvents: function(otherDv) {\n this.forceUpdate = registerUpdate(this);\n setScrollLock(this, true, false);\n registerScroll(this, otherDv);\n },\n setShowDifferences: function(val) {\n val = val !== false;\n if (val != this.showDifferences) {\n this.showDifferences = val;\n this.forceUpdate(\"full\");\n }\n }\n };\n\n function ensureDiff(dv) {\n if (dv.diffOutOfDate) {\n dv.diff = getDiff(dv.orig.getValue(), dv.edit.getValue(), dv.mv.options.ignoreWhitespace);\n dv.chunks = getChunks(dv.diff);\n dv.diffOutOfDate = false;\n CodeMirror.signal(dv.edit, \"updateDiff\", dv.diff);\n }\n }\n\n var updating = false;\n function registerUpdate(dv) {\n var edit = {from: 0, to: 0, marked: []};\n var orig = {from: 0, to: 0, marked: []};\n var debounceChange, updatingFast = false;\n function update(mode) {\n updating = true;\n updatingFast = false;\n if (mode == \"full\") {\n if (dv.svg) clear(dv.svg);\n if (dv.copyButtons) clear(dv.copyButtons);\n clearMarks(dv.edit, edit.marked, dv.classes);\n clearMarks(dv.orig, orig.marked, dv.classes);\n edit.from = edit.to = orig.from = orig.to = 0;\n }\n ensureDiff(dv);\n if (dv.showDifferences) {\n updateMarks(dv.edit, dv.diff, edit, DIFF_INSERT, dv.classes);\n updateMarks(dv.orig, dv.diff, orig, DIFF_DELETE, dv.classes);\n }\n\n if (dv.mv.options.connect == \"align\")\n alignChunks(dv);\n makeConnections(dv);\n if (dv.needsScrollSync != null) syncScroll(dv, dv.needsScrollSync)\n\n updating = false;\n }\n function setDealign(fast) {\n if (updating) return;\n dv.dealigned = true;\n set(fast);\n }\n function set(fast) {\n if (updating || updatingFast) return;\n clearTimeout(debounceChange);\n if (fast === true) updatingFast = true;\n debounceChange = setTimeout(update, fast === true ? 20 : 250);\n }\n function change(_cm, change) {\n if (!dv.diffOutOfDate) {\n dv.diffOutOfDate = true;\n edit.from = edit.to = orig.from = orig.to = 0;\n }\n // Update faster when a line was added/removed\n setDealign(change.text.length - 1 != change.to.line - change.from.line);\n }\n function swapDoc() {\n dv.diffOutOfDate = true;\n dv.dealigned = true;\n update(\"full\");\n }\n dv.edit.on(\"change\", change);\n dv.orig.on(\"change\", change);\n dv.edit.on(\"swapDoc\", swapDoc);\n dv.orig.on(\"swapDoc\", swapDoc);\n if (dv.mv.options.connect == \"align\") {\n CodeMirror.on(dv.edit.state.trackAlignable, \"realign\", setDealign)\n CodeMirror.on(dv.orig.state.trackAlignable, \"realign\", setDealign)\n }\n dv.edit.on(\"viewportChange\", function() { set(false); });\n dv.orig.on(\"viewportChange\", function() { set(false); });\n update();\n return update;\n }\n\n function registerScroll(dv, otherDv) {\n dv.edit.on(\"scroll\", function() {\n syncScroll(dv, true) && makeConnections(dv);\n });\n dv.orig.on(\"scroll\", function() {\n syncScroll(dv, false) && makeConnections(dv);\n if (otherDv) syncScroll(otherDv, true) && makeConnections(otherDv);\n });\n }\n\n function syncScroll(dv, toOrig) {\n // Change handler will do a refresh after a timeout when diff is out of date\n if (dv.diffOutOfDate) {\n if (dv.lockScroll && dv.needsScrollSync == null) dv.needsScrollSync = toOrig\n return false\n }\n dv.needsScrollSync = null\n if (!dv.lockScroll) return true;\n var editor, other, now = +new Date;\n if (toOrig) { editor = dv.edit; other = dv.orig; }\n else { editor = dv.orig; other = dv.edit; }\n // Don't take action if the position of this editor was recently set\n // (to prevent feedback loops)\n if (editor.state.scrollSetBy == dv && (editor.state.scrollSetAt || 0) + 250 > now) return false;\n\n var sInfo = editor.getScrollInfo();\n if (dv.mv.options.connect == \"align\") {\n targetPos = sInfo.top;\n } else {\n var halfScreen = .5 * sInfo.clientHeight, midY = sInfo.top + halfScreen;\n var mid = editor.lineAtHeight(midY, \"local\");\n var around = chunkBoundariesAround(dv.chunks, mid, toOrig);\n var off = getOffsets(editor, toOrig ? around.edit : around.orig);\n var offOther = getOffsets(other, toOrig ? around.orig : around.edit);\n var ratio = (midY - off.top) / (off.bot - off.top);\n var targetPos = (offOther.top - halfScreen) + ratio * (offOther.bot - offOther.top);\n\n var botDist, mix;\n // Some careful tweaking to make sure no space is left out of view\n // when scrolling to top or bottom.\n if (targetPos > sInfo.top && (mix = sInfo.top / halfScreen) < 1) {\n targetPos = targetPos * mix + sInfo.top * (1 - mix);\n } else if ((botDist = sInfo.height - sInfo.clientHeight - sInfo.top) < halfScreen) {\n var otherInfo = other.getScrollInfo();\n var botDistOther = otherInfo.height - otherInfo.clientHeight - targetPos;\n if (botDistOther > botDist && (mix = botDist / halfScreen) < 1)\n targetPos = targetPos * mix + (otherInfo.height - otherInfo.clientHeight - botDist) * (1 - mix);\n }\n }\n\n other.scrollTo(sInfo.left, targetPos);\n other.state.scrollSetAt = now;\n other.state.scrollSetBy = dv;\n return true;\n }\n\n function getOffsets(editor, around) {\n var bot = around.after;\n if (bot == null) bot = editor.lastLine() + 1;\n return {top: editor.heightAtLine(around.before || 0, \"local\"),\n bot: editor.heightAtLine(bot, \"local\")};\n }\n\n function setScrollLock(dv, val, action) {\n dv.lockScroll = val;\n if (val && action != false) syncScroll(dv, DIFF_INSERT) && makeConnections(dv);\n (val ? CodeMirror.addClass : CodeMirror.rmClass)(dv.lockButton, \"CodeMirror-merge-scrolllock-enabled\");\n }\n\n // Updating the marks for editor content\n\n function removeClass(editor, line, classes) {\n var locs = classes.classLocation\n for (var i = 0; i < locs.length; i++) {\n editor.removeLineClass(line, locs[i], classes.chunk);\n editor.removeLineClass(line, locs[i], classes.start);\n editor.removeLineClass(line, locs[i], classes.end);\n }\n }\n\n function clearMarks(editor, arr, classes) {\n for (var i = 0; i < arr.length; ++i) {\n var mark = arr[i];\n if (mark instanceof CodeMirror.TextMarker)\n mark.clear();\n else if (mark.parent)\n removeClass(editor, mark, classes);\n }\n arr.length = 0;\n }\n\n // FIXME maybe add a margin around viewport to prevent too many updates\n function updateMarks(editor, diff, state, type, classes) {\n var vp = editor.getViewport();\n editor.operation(function() {\n if (state.from == state.to || vp.from - state.to > 20 || state.from - vp.to > 20) {\n clearMarks(editor, state.marked, classes);\n markChanges(editor, diff, type, state.marked, vp.from, vp.to, classes);\n state.from = vp.from; state.to = vp.to;\n } else {\n if (vp.from < state.from) {\n markChanges(editor, diff, type, state.marked, vp.from, state.from, classes);\n state.from = vp.from;\n }\n if (vp.to > state.to) {\n markChanges(editor, diff, type, state.marked, state.to, vp.to, classes);\n state.to = vp.to;\n }\n }\n });\n }\n\n function addClass(editor, lineNr, classes, main, start, end) {\n var locs = classes.classLocation, line = editor.getLineHandle(lineNr);\n for (var i = 0; i < locs.length; i++) {\n if (main) editor.addLineClass(line, locs[i], classes.chunk);\n if (start) editor.addLineClass(line, locs[i], classes.start);\n if (end) editor.addLineClass(line, locs[i], classes.end);\n }\n return line;\n }\n\n function markChanges(editor, diff, type, marks, from, to, classes) {\n var pos = Pos(0, 0);\n var top = Pos(from, 0), bot = editor.clipPos(Pos(to - 1));\n var cls = type == DIFF_DELETE ? classes.del : classes.insert;\n function markChunk(start, end) {\n var bfrom = Math.max(from, start), bto = Math.min(to, end);\n for (var i = bfrom; i < bto; ++i)\n marks.push(addClass(editor, i, classes, true, i == start, i == end - 1));\n // When the chunk is empty, make sure a horizontal line shows up\n if (start == end && bfrom == end && bto == end) {\n if (bfrom)\n marks.push(addClass(editor, bfrom - 1, classes, false, false, true));\n else\n marks.push(addClass(editor, bfrom, classes, false, true, false));\n }\n }\n\n var chunkStart = 0, pending = false;\n for (var i = 0; i < diff.length; ++i) {\n var part = diff[i], tp = part[0], str = part[1];\n if (tp == DIFF_EQUAL) {\n var cleanFrom = pos.line + (startOfLineClean(diff, i) ? 0 : 1);\n moveOver(pos, str);\n var cleanTo = pos.line + (endOfLineClean(diff, i) ? 1 : 0);\n if (cleanTo > cleanFrom) {\n if (pending) { markChunk(chunkStart, cleanFrom); pending = false }\n chunkStart = cleanTo;\n }\n } else {\n pending = true\n if (tp == type) {\n var end = moveOver(pos, str, true);\n var a = posMax(top, pos), b = posMin(bot, end);\n if (!posEq(a, b))\n marks.push(editor.markText(a, b, {className: cls}));\n pos = end;\n }\n }\n }\n if (pending) markChunk(chunkStart, pos.line + 1);\n }\n\n // Updating the gap between editor and original\n\n function makeConnections(dv) {\n if (!dv.showDifferences) return;\n\n if (dv.svg) {\n clear(dv.svg);\n var w = dv.gap.offsetWidth;\n attrs(dv.svg, \"width\", w, \"height\", dv.gap.offsetHeight);\n }\n if (dv.copyButtons) clear(dv.copyButtons);\n\n var vpEdit = dv.edit.getViewport(), vpOrig = dv.orig.getViewport();\n var outerTop = dv.mv.wrap.getBoundingClientRect().top\n var sTopEdit = outerTop - dv.edit.getScrollerElement().getBoundingClientRect().top + dv.edit.getScrollInfo().top\n var sTopOrig = outerTop - dv.orig.getScrollerElement().getBoundingClientRect().top + dv.orig.getScrollInfo().top;\n for (var i = 0; i < dv.chunks.length; i++) {\n var ch = dv.chunks[i];\n if (ch.editFrom <= vpEdit.to && ch.editTo >= vpEdit.from &&\n ch.origFrom <= vpOrig.to && ch.origTo >= vpOrig.from)\n drawConnectorsForChunk(dv, ch, sTopOrig, sTopEdit, w);\n }\n }\n\n function getMatchingOrigLine(editLine, chunks) {\n var editStart = 0, origStart = 0;\n for (var i = 0; i < chunks.length; i++) {\n var chunk = chunks[i];\n if (chunk.editTo > editLine && chunk.editFrom <= editLine) return null;\n if (chunk.editFrom > editLine) break;\n editStart = chunk.editTo;\n origStart = chunk.origTo;\n }\n return origStart + (editLine - editStart);\n }\n\n // Combines information about chunks and widgets/markers to return\n // an array of lines, in a single editor, that probably need to be\n // aligned with their counterparts in the editor next to it.\n function alignableFor(cm, chunks, isOrig) {\n var tracker = cm.state.trackAlignable\n var start = cm.firstLine(), trackI = 0\n var result = []\n for (var i = 0;; i++) {\n var chunk = chunks[i]\n var chunkStart = !chunk ? 1e9 : isOrig ? chunk.origFrom : chunk.editFrom\n for (; trackI < tracker.alignable.length; trackI += 2) {\n var n = tracker.alignable[trackI] + 1\n if (n <= start) continue\n if (n <= chunkStart) result.push(n)\n else break\n }\n if (!chunk) break\n result.push(start = isOrig ? chunk.origTo : chunk.editTo)\n }\n return result\n }\n\n // Given information about alignable lines in two editors, fill in\n // the result (an array of three-element arrays) to reflect the\n // lines that need to be aligned with each other.\n function mergeAlignable(result, origAlignable, chunks, setIndex) {\n var rI = 0, origI = 0, chunkI = 0, diff = 0\n outer: for (;; rI++) {\n var nextR = result[rI], nextO = origAlignable[origI]\n if (!nextR && nextO == null) break\n\n var rLine = nextR ? nextR[0] : 1e9, oLine = nextO == null ? 1e9 : nextO\n while (chunkI < chunks.length) {\n var chunk = chunks[chunkI]\n if (chunk.origFrom <= oLine && chunk.origTo > oLine) {\n origI++\n rI--\n continue outer;\n }\n if (chunk.editTo > rLine) {\n if (chunk.editFrom <= rLine) continue outer;\n break\n }\n diff += (chunk.origTo - chunk.origFrom) - (chunk.editTo - chunk.editFrom)\n chunkI++\n }\n if (rLine == oLine - diff) {\n nextR[setIndex] = oLine\n origI++\n } else if (rLine < oLine - diff) {\n nextR[setIndex] = rLine + diff\n } else {\n var record = [oLine - diff, null, null]\n record[setIndex] = oLine\n result.splice(rI, 0, record)\n origI++\n }\n }\n }\n\n function findAlignedLines(dv, other) {\n var alignable = alignableFor(dv.edit, dv.chunks, false), result = []\n if (other) for (var i = 0, j = 0; i < other.chunks.length; i++) {\n var n = other.chunks[i].editTo\n while (j < alignable.length && alignable[j] < n) j++\n if (j == alignable.length || alignable[j] != n) alignable.splice(j++, 0, n)\n }\n for (var i = 0; i < alignable.length; i++)\n result.push([alignable[i], null, null])\n\n mergeAlignable(result, alignableFor(dv.orig, dv.chunks, true), dv.chunks, 1)\n if (other)\n mergeAlignable(result, alignableFor(other.orig, other.chunks, true), other.chunks, 2)\n\n return result\n }\n\n function alignChunks(dv, force) {\n if (!dv.dealigned && !force) return;\n if (!dv.orig.curOp) return dv.orig.operation(function() {\n alignChunks(dv, force);\n });\n\n dv.dealigned = false;\n var other = dv.mv.left == dv ? dv.mv.right : dv.mv.left;\n if (other) {\n ensureDiff(other);\n other.dealigned = false;\n }\n var linesToAlign = findAlignedLines(dv, other);\n\n // Clear old aligners\n var aligners = dv.mv.aligners;\n for (var i = 0; i < aligners.length; i++)\n aligners[i].clear();\n aligners.length = 0;\n\n var cm = [dv.edit, dv.orig], scroll = [], offset = []\n if (other) cm.push(other.orig);\n for (var i = 0; i < cm.length; i++) {\n scroll.push(cm[i].getScrollInfo().top);\n offset.push(-cm[i].getScrollerElement().getBoundingClientRect().top)\n }\n\n if (offset[0] != offset[1] || cm.length == 3 && offset[1] != offset[2])\n alignLines(cm, offset, [0, 0, 0], aligners)\n for (var ln = 0; ln < linesToAlign.length; ln++)\n alignLines(cm, offset, linesToAlign[ln], aligners);\n\n for (var i = 0; i < cm.length; i++)\n cm[i].scrollTo(null, scroll[i]);\n }\n\n function alignLines(cm, cmOffset, lines, aligners) {\n var maxOffset = -1e8, offset = [];\n for (var i = 0; i < cm.length; i++) if (lines[i] != null) {\n var off = cm[i].heightAtLine(lines[i], \"local\") - cmOffset[i];\n offset[i] = off;\n maxOffset = Math.max(maxOffset, off);\n }\n for (var i = 0; i < cm.length; i++) if (lines[i] != null) {\n var diff = maxOffset - offset[i];\n if (diff > 1)\n aligners.push(padAbove(cm[i], lines[i], diff));\n }\n }\n\n function padAbove(cm, line, size) {\n var above = true;\n if (line > cm.lastLine()) {\n line--;\n above = false;\n }\n var elt = document.createElement(\"div\");\n elt.className = \"CodeMirror-merge-spacer\";\n elt.style.height = size + \"px\"; elt.style.minWidth = \"1px\";\n return cm.addLineWidget(line, elt, {height: size, above: above, mergeSpacer: true, handleMouseEvents: true});\n }\n\n function drawConnectorsForChunk(dv, chunk, sTopOrig, sTopEdit, w) {\n var flip = dv.type == \"left\";\n var top = dv.orig.heightAtLine(chunk.origFrom, \"local\", true) - sTopOrig;\n if (dv.svg) {\n var topLpx = top;\n var topRpx = dv.edit.heightAtLine(chunk.editFrom, \"local\", true) - sTopEdit;\n if (flip) { var tmp = topLpx; topLpx = topRpx; topRpx = tmp; }\n var botLpx = dv.orig.heightAtLine(chunk.origTo, \"local\", true) - sTopOrig;\n var botRpx = dv.edit.heightAtLine(chunk.editTo, \"local\", true) - sTopEdit;\n if (flip) { var tmp = botLpx; botLpx = botRpx; botRpx = tmp; }\n var curveTop = \" C \" + w/2 + \" \" + topRpx + \" \" + w/2 + \" \" + topLpx + \" \" + (w + 2) + \" \" + topLpx;\n var curveBot = \" C \" + w/2 + \" \" + botLpx + \" \" + w/2 + \" \" + botRpx + \" -1 \" + botRpx;\n attrs(dv.svg.appendChild(document.createElementNS(svgNS, \"path\")),\n \"d\", \"M -1 \" + topRpx + curveTop + \" L \" + (w + 2) + \" \" + botLpx + curveBot + \" z\",\n \"class\", dv.classes.connect);\n }\n if (dv.copyButtons) {\n var copy = dv.copyButtons.appendChild(elt(\"div\", dv.type == \"left\" ? \"\\u21dd\" : \"\\u21dc\",\n \"CodeMirror-merge-copy\"));\n var editOriginals = dv.mv.options.allowEditingOriginals;\n copy.title = dv.edit.phrase(editOriginals ? \"Push to left\" : \"Revert chunk\");\n copy.chunk = chunk;\n copy.style.top = (chunk.origTo > chunk.origFrom ? top : dv.edit.heightAtLine(chunk.editFrom, \"local\") - sTopEdit) + \"px\";\n copy.setAttribute(\"role\", \"button\");\n copy.setAttribute(\"tabindex\", \"0\");\n copy.setAttribute(\"aria-label\", copy.title);\n\n if (editOriginals) {\n var topReverse = dv.edit.heightAtLine(chunk.editFrom, \"local\") - sTopEdit;\n var copyReverse = dv.copyButtons.appendChild(elt(\"div\", dv.type == \"right\" ? \"\\u21dd\" : \"\\u21dc\",\n \"CodeMirror-merge-copy-reverse\"));\n copyReverse.title = \"Push to right\";\n copyReverse.chunk = {editFrom: chunk.origFrom, editTo: chunk.origTo,\n origFrom: chunk.editFrom, origTo: chunk.editTo};\n copyReverse.style.top = topReverse + \"px\";\n dv.type == \"right\" ? copyReverse.style.left = \"2px\" : copyReverse.style.right = \"2px\";\n copyReverse.setAttribute(\"role\", \"button\");\n copyReverse.setAttribute(\"tabindex\", \"0\");\n copyReverse.setAttribute(\"aria-label\", copyReverse.title);\n }\n }\n }\n\n function copyChunk(dv, to, from, chunk) {\n if (dv.diffOutOfDate) return;\n var origStart = chunk.origTo > from.lastLine() ? Pos(chunk.origFrom - 1) : Pos(chunk.origFrom, 0)\n var origEnd = Pos(chunk.origTo, 0)\n var editStart = chunk.editTo > to.lastLine() ? Pos(chunk.editFrom - 1) : Pos(chunk.editFrom, 0)\n var editEnd = Pos(chunk.editTo, 0)\n var handler = dv.mv.options.revertChunk\n if (handler)\n handler(dv.mv, from, origStart, origEnd, to, editStart, editEnd)\n else\n to.replaceRange(from.getRange(origStart, origEnd), editStart, editEnd)\n }\n\n // Merge view, containing 0, 1, or 2 diff views.\n\n var MergeView = CodeMirror.MergeView = function(node, options) {\n if (!(this instanceof MergeView)) return new MergeView(node, options);\n\n this.options = options;\n var origLeft = options.origLeft, origRight = options.origRight == null ? options.orig : options.origRight;\n\n var hasLeft = origLeft != null, hasRight = origRight != null;\n var panes = 1 + (hasLeft ? 1 : 0) + (hasRight ? 1 : 0);\n var wrap = [], left = this.left = null, right = this.right = null;\n var self = this;\n\n if (hasLeft) {\n left = this.left = new DiffView(this, \"left\");\n var leftPane = elt(\"div\", null, \"CodeMirror-merge-pane CodeMirror-merge-left\");\n wrap.push(leftPane);\n wrap.push(buildGap(left));\n }\n\n var editPane = elt(\"div\", null, \"CodeMirror-merge-pane CodeMirror-merge-editor\");\n wrap.push(editPane);\n\n if (hasRight) {\n right = this.right = new DiffView(this, \"right\");\n wrap.push(buildGap(right));\n var rightPane = elt(\"div\", null, \"CodeMirror-merge-pane CodeMirror-merge-right\");\n wrap.push(rightPane);\n }\n\n (hasRight ? rightPane : editPane).className += \" CodeMirror-merge-pane-rightmost\";\n\n wrap.push(elt(\"div\", null, null, \"height: 0; clear: both;\"));\n\n var wrapElt = this.wrap = node.appendChild(elt(\"div\", wrap, \"CodeMirror-merge CodeMirror-merge-\" + panes + \"pane\"));\n this.edit = CodeMirror(editPane, copyObj(options));\n\n if (left) left.init(leftPane, origLeft, options);\n if (right) right.init(rightPane, origRight, options);\n if (options.collapseIdentical)\n this.editor().operation(function() {\n collapseIdenticalStretches(self, options.collapseIdentical);\n });\n if (options.connect == \"align\") {\n this.aligners = [];\n alignChunks(this.left || this.right, true);\n }\n if (left) left.registerEvents(right)\n if (right) right.registerEvents(left)\n\n\n var onResize = function() {\n if (left) makeConnections(left);\n if (right) makeConnections(right);\n };\n CodeMirror.on(window, \"resize\", onResize);\n var resizeInterval = setInterval(function() {\n for (var p = wrapElt.parentNode; p && p != document.body; p = p.parentNode) {}\n if (!p) { clearInterval(resizeInterval); CodeMirror.off(window, \"resize\", onResize); }\n }, 5000);\n };\n\n function buildGap(dv) {\n var lock = dv.lockButton = elt(\"div\", null, \"CodeMirror-merge-scrolllock\");\n lock.setAttribute(\"role\", \"button\");\n lock.setAttribute(\"tabindex\", \"0\");\n var lockWrap = elt(\"div\", [lock], \"CodeMirror-merge-scrolllock-wrap\");\n CodeMirror.on(lock, \"click\", function() { setScrollLock(dv, !dv.lockScroll); });\n CodeMirror.on(lock, \"keyup\", function(e) { (e.key === \"Enter\" || e.code === \"Space\") && setScrollLock(dv, !dv.lockScroll); });\n var gapElts = [lockWrap];\n if (dv.mv.options.revertButtons !== false) {\n dv.copyButtons = elt(\"div\", null, \"CodeMirror-merge-copybuttons-\" + dv.type);\n var copyButtons = function(e) {\n var node = e.target || e.srcElement;\n if (!node.chunk) return;\n if (node.className == \"CodeMirror-merge-copy-reverse\") {\n copyChunk(dv, dv.orig, dv.edit, node.chunk);\n return;\n }\n copyChunk(dv, dv.edit, dv.orig, node.chunk);\n }\n CodeMirror.on(dv.copyButtons, \"click\", copyButtons);\n CodeMirror.on(dv.copyButtons, \"keyup\", function(e) { (e.key === \"Enter\" || e.code === \"Space\") && copyButtons(e); });\n gapElts.unshift(dv.copyButtons);\n }\n if (dv.mv.options.connect != \"align\") {\n var svg = document.createElementNS && document.createElementNS(svgNS, \"svg\");\n if (svg && !svg.createSVGRect) svg = null;\n dv.svg = svg;\n if (svg) gapElts.push(svg);\n }\n\n return dv.gap = elt(\"div\", gapElts, \"CodeMirror-merge-gap\");\n }\n\n MergeView.prototype = {\n constructor: MergeView,\n editor: function() { return this.edit; },\n rightOriginal: function() { return this.right && this.right.orig; },\n leftOriginal: function() { return this.left && this.left.orig; },\n setShowDifferences: function(val) {\n if (this.right) this.right.setShowDifferences(val);\n if (this.left) this.left.setShowDifferences(val);\n },\n rightChunks: function() {\n if (this.right) { ensureDiff(this.right); return this.right.chunks; }\n },\n leftChunks: function() {\n if (this.left) { ensureDiff(this.left); return this.left.chunks; }\n }\n };\n\n function asString(obj) {\n if (typeof obj == \"string\") return obj;\n else return obj.getValue();\n }\n\n // Operations on diffs\n var dmp;\n function getDiff(a, b, ignoreWhitespace) {\n if (!dmp) dmp = new diff_match_patch();\n\n var diff = dmp.diff_main(a, b);\n // The library sometimes leaves in empty parts, which confuse the algorithm\n for (var i = 0; i < diff.length; ++i) {\n var part = diff[i];\n if (ignoreWhitespace ? !/[^ \\t]/.test(part[1]) : !part[1]) {\n diff.splice(i--, 1);\n } else if (i && diff[i - 1][0] == part[0]) {\n diff.splice(i--, 1);\n diff[i][1] += part[1];\n }\n }\n return diff;\n }\n\n function getChunks(diff) {\n var chunks = [];\n if (!diff.length) return chunks;\n var startEdit = 0, startOrig = 0;\n var edit = Pos(0, 0), orig = Pos(0, 0);\n for (var i = 0; i < diff.length; ++i) {\n var part = diff[i], tp = part[0];\n if (tp == DIFF_EQUAL) {\n var startOff = !startOfLineClean(diff, i) || edit.line < startEdit || orig.line < startOrig ? 1 : 0;\n var cleanFromEdit = edit.line + startOff, cleanFromOrig = orig.line + startOff;\n moveOver(edit, part[1], null, orig);\n var endOff = endOfLineClean(diff, i) ? 1 : 0;\n var cleanToEdit = edit.line + endOff, cleanToOrig = orig.line + endOff;\n if (cleanToEdit > cleanFromEdit) {\n if (i) chunks.push({origFrom: startOrig, origTo: cleanFromOrig,\n editFrom: startEdit, editTo: cleanFromEdit});\n startEdit = cleanToEdit; startOrig = cleanToOrig;\n }\n } else {\n moveOver(tp == DIFF_INSERT ? edit : orig, part[1]);\n }\n }\n if (startEdit <= edit.line || startOrig <= orig.line)\n chunks.push({origFrom: startOrig, origTo: orig.line + 1,\n editFrom: startEdit, editTo: edit.line + 1});\n return chunks;\n }\n\n function endOfLineClean(diff, i) {\n if (i == diff.length - 1) return true;\n var next = diff[i + 1][1];\n if ((next.length == 1 && i < diff.length - 2) || next.charCodeAt(0) != 10) return false;\n if (i == diff.length - 2) return true;\n next = diff[i + 2][1];\n return (next.length > 1 || i == diff.length - 3) && next.charCodeAt(0) == 10;\n }\n\n function startOfLineClean(diff, i) {\n if (i == 0) return true;\n var last = diff[i - 1][1];\n if (last.charCodeAt(last.length - 1) != 10) return false;\n if (i == 1) return true;\n last = diff[i - 2][1];\n return last.charCodeAt(last.length - 1) == 10;\n }\n\n function chunkBoundariesAround(chunks, n, nInEdit) {\n var beforeE, afterE, beforeO, afterO;\n for (var i = 0; i < chunks.length; i++) {\n var chunk = chunks[i];\n var fromLocal = nInEdit ? chunk.editFrom : chunk.origFrom;\n var toLocal = nInEdit ? chunk.editTo : chunk.origTo;\n if (afterE == null) {\n if (fromLocal > n) { afterE = chunk.editFrom; afterO = chunk.origFrom; }\n else if (toLocal > n) { afterE = chunk.editTo; afterO = chunk.origTo; }\n }\n if (toLocal <= n) { beforeE = chunk.editTo; beforeO = chunk.origTo; }\n else if (fromLocal <= n) { beforeE = chunk.editFrom; beforeO = chunk.origFrom; }\n }\n return {edit: {before: beforeE, after: afterE}, orig: {before: beforeO, after: afterO}};\n }\n\n function collapseSingle(cm, from, to) {\n cm.addLineClass(from, \"wrap\", \"CodeMirror-merge-collapsed-line\");\n var widget = document.createElement(\"span\");\n widget.className = \"CodeMirror-merge-collapsed-widget\";\n widget.title = cm.phrase(\"Identical text collapsed. Click to expand.\");\n var mark = cm.markText(Pos(from, 0), Pos(to - 1), {\n inclusiveLeft: true,\n inclusiveRight: true,\n replacedWith: widget,\n clearOnEnter: true\n });\n function clear() {\n mark.clear();\n cm.removeLineClass(from, \"wrap\", \"CodeMirror-merge-collapsed-line\");\n }\n if (mark.explicitlyCleared) clear();\n CodeMirror.on(widget, \"click\", clear);\n mark.on(\"clear\", clear);\n CodeMirror.on(widget, \"click\", clear);\n return {mark: mark, clear: clear};\n }\n\n function collapseStretch(size, editors) {\n var marks = [];\n function clear() {\n for (var i = 0; i < marks.length; i++) marks[i].clear();\n }\n for (var i = 0; i < editors.length; i++) {\n var editor = editors[i];\n var mark = collapseSingle(editor.cm, editor.line, editor.line + size);\n marks.push(mark);\n mark.mark.on(\"clear\", clear);\n }\n return marks[0].mark;\n }\n\n function unclearNearChunks(dv, margin, off, clear) {\n for (var i = 0; i < dv.chunks.length; i++) {\n var chunk = dv.chunks[i];\n for (var l = chunk.editFrom - margin; l < chunk.editTo + margin; l++) {\n var pos = l + off;\n if (pos >= 0 && pos < clear.length) clear[pos] = false;\n }\n }\n }\n\n function collapseIdenticalStretches(mv, margin) {\n if (typeof margin != \"number\") margin = 2;\n var clear = [], edit = mv.editor(), off = edit.firstLine();\n for (var l = off, e = edit.lastLine(); l <= e; l++) clear.push(true);\n if (mv.left) unclearNearChunks(mv.left, margin, off, clear);\n if (mv.right) unclearNearChunks(mv.right, margin, off, clear);\n\n for (var i = 0; i < clear.length; i++) {\n if (clear[i]) {\n var line = i + off;\n for (var size = 1; i < clear.length - 1 && clear[i + 1]; i++, size++) {}\n if (size > margin) {\n var editors = [{line: line, cm: edit}];\n if (mv.left) editors.push({line: getMatchingOrigLine(line, mv.left.chunks), cm: mv.left.orig});\n if (mv.right) editors.push({line: getMatchingOrigLine(line, mv.right.chunks), cm: mv.right.orig});\n var mark = collapseStretch(size, editors);\n if (mv.options.onCollapse) mv.options.onCollapse(mv, line, size, mark);\n }\n }\n }\n }\n\n // General utilities\n\n function elt(tag, content, className, style) {\n var e = document.createElement(tag);\n if (className) e.className = className;\n if (style) e.style.cssText = style;\n if (typeof content == \"string\") e.appendChild(document.createTextNode(content));\n else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]);\n return e;\n }\n\n function clear(node) {\n for (var count = node.childNodes.length; count > 0; --count)\n node.removeChild(node.firstChild);\n }\n\n function attrs(elt) {\n for (var i = 1; i < arguments.length; i += 2)\n elt.setAttribute(arguments[i], arguments[i+1]);\n }\n\n function copyObj(obj, target) {\n if (!target) target = {};\n for (var prop in obj) if (obj.hasOwnProperty(prop)) target[prop] = obj[prop];\n return target;\n }\n\n function moveOver(pos, str, copy, other) {\n var out = copy ? Pos(pos.line, pos.ch) : pos, at = 0;\n for (;;) {\n var nl = str.indexOf(\"\\n\", at);\n if (nl == -1) break;\n ++out.line;\n if (other) ++other.line;\n at = nl + 1;\n }\n out.ch = (at ? 0 : out.ch) + (str.length - at);\n if (other) other.ch = (at ? 0 : other.ch) + (str.length - at);\n return out;\n }\n\n // Tracks collapsed markers and line widgets, in order to be able to\n // accurately align the content of two editors.\n\n var F_WIDGET = 1, F_WIDGET_BELOW = 2, F_MARKER = 4\n\n function TrackAlignable(cm) {\n this.cm = cm\n this.alignable = []\n this.height = cm.doc.height\n var self = this\n cm.on(\"markerAdded\", function(_, marker) {\n if (!marker.collapsed) return\n var found = marker.find(1)\n if (found != null) self.set(found.line, F_MARKER)\n })\n cm.on(\"markerCleared\", function(_, marker, _min, max) {\n if (max != null && marker.collapsed)\n self.check(max, F_MARKER, self.hasMarker)\n })\n cm.on(\"markerChanged\", this.signal.bind(this))\n cm.on(\"lineWidgetAdded\", function(_, widget, lineNo) {\n if (widget.mergeSpacer) return\n if (widget.above) self.set(lineNo - 1, F_WIDGET_BELOW)\n else self.set(lineNo, F_WIDGET)\n })\n cm.on(\"lineWidgetCleared\", function(_, widget, lineNo) {\n if (widget.mergeSpacer) return\n if (widget.above) self.check(lineNo - 1, F_WIDGET_BELOW, self.hasWidgetBelow)\n else self.check(lineNo, F_WIDGET, self.hasWidget)\n })\n cm.on(\"lineWidgetChanged\", this.signal.bind(this))\n cm.on(\"change\", function(_, change) {\n var start = change.from.line, nBefore = change.to.line - change.from.line\n var nAfter = change.text.length - 1, end = start + nAfter\n if (nBefore || nAfter) self.map(start, nBefore, nAfter)\n self.check(end, F_MARKER, self.hasMarker)\n if (nBefore || nAfter) self.check(change.from.line, F_MARKER, self.hasMarker)\n })\n cm.on(\"viewportChange\", function() {\n if (self.cm.doc.height != self.height) self.signal()\n })\n }\n\n TrackAlignable.prototype = {\n signal: function() {\n CodeMirror.signal(this, \"realign\")\n this.height = this.cm.doc.height\n },\n\n set: function(n, flags) {\n var pos = -1\n for (; pos < this.alignable.length; pos += 2) {\n var diff = this.alignable[pos] - n\n if (diff == 0) {\n if ((this.alignable[pos + 1] & flags) == flags) return\n this.alignable[pos + 1] |= flags\n this.signal()\n return\n }\n if (diff > 0) break\n }\n this.signal()\n this.alignable.splice(pos, 0, n, flags)\n },\n\n find: function(n) {\n for (var i = 0; i < this.alignable.length; i += 2)\n if (this.alignable[i] == n) return i\n return -1\n },\n\n check: function(n, flag, pred) {\n var found = this.find(n)\n if (found == -1 || !(this.alignable[found + 1] & flag)) return\n if (!pred.call(this, n)) {\n this.signal()\n var flags = this.alignable[found + 1] & ~flag\n if (flags) this.alignable[found + 1] = flags\n else this.alignable.splice(found, 2)\n }\n },\n\n hasMarker: function(n) {\n var handle = this.cm.getLineHandle(n)\n if (handle.markedSpans) for (var i = 0; i < handle.markedSpans.length; i++)\n if (handle.markedSpans[i].marker.collapsed && handle.markedSpans[i].to != null)\n return true\n return false\n },\n\n hasWidget: function(n) {\n var handle = this.cm.getLineHandle(n)\n if (handle.widgets) for (var i = 0; i < handle.widgets.length; i++)\n if (!handle.widgets[i].above && !handle.widgets[i].mergeSpacer) return true\n return false\n },\n\n hasWidgetBelow: function(n) {\n if (n == this.cm.lastLine()) return false\n var handle = this.cm.getLineHandle(n + 1)\n if (handle.widgets) for (var i = 0; i < handle.widgets.length; i++)\n if (handle.widgets[i].above && !handle.widgets[i].mergeSpacer) return true\n return false\n },\n\n map: function(from, nBefore, nAfter) {\n var diff = nAfter - nBefore, to = from + nBefore, widgetFrom = -1, widgetTo = -1\n for (var i = 0; i < this.alignable.length; i += 2) {\n var n = this.alignable[i]\n if (n == from && (this.alignable[i + 1] & F_WIDGET_BELOW)) widgetFrom = i\n if (n == to && (this.alignable[i + 1] & F_WIDGET_BELOW)) widgetTo = i\n if (n <= from) continue\n else if (n < to) this.alignable.splice(i--, 2)\n else this.alignable[i] += diff\n }\n if (widgetFrom > -1) {\n var flags = this.alignable[widgetFrom + 1]\n if (flags == F_WIDGET_BELOW) this.alignable.splice(widgetFrom, 2)\n else this.alignable[widgetFrom + 1] = flags & ~F_WIDGET_BELOW\n }\n if (widgetTo > -1 && nAfter)\n this.set(from + nAfter, F_WIDGET_BELOW)\n }\n }\n\n function posMin(a, b) { return (a.line - b.line || a.ch - b.ch) < 0 ? a : b; }\n function posMax(a, b) { return (a.line - b.line || a.ch - b.ch) > 0 ? a : b; }\n function posEq(a, b) { return a.line == b.line && a.ch == b.ch; }\n\n function findPrevDiff(chunks, start, isOrig) {\n for (var i = chunks.length - 1; i >= 0; i--) {\n var chunk = chunks[i];\n var to = (isOrig ? chunk.origTo : chunk.editTo) - 1;\n if (to < start) return to;\n }\n }\n\n function findNextDiff(chunks, start, isOrig) {\n for (var i = 0; i < chunks.length; i++) {\n var chunk = chunks[i];\n var from = (isOrig ? chunk.origFrom : chunk.editFrom);\n if (from > start) return from;\n }\n }\n\n function goNearbyDiff(cm, dir) {\n var found = null, views = cm.state.diffViews, line = cm.getCursor().line;\n if (views) for (var i = 0; i < views.length; i++) {\n var dv = views[i], isOrig = cm == dv.orig;\n ensureDiff(dv);\n var pos = dir < 0 ? findPrevDiff(dv.chunks, line, isOrig) : findNextDiff(dv.chunks, line, isOrig);\n if (pos != null && (found == null || (dir < 0 ? pos > found : pos < found)))\n found = pos;\n }\n if (found != null)\n cm.setCursor(found, 0);\n else\n return CodeMirror.Pass;\n }\n\n CodeMirror.commands.goNextDiff = function(cm) {\n return goNearbyDiff(cm, 1);\n };\n CodeMirror.commands.goPrevDiff = function(cm) {\n return goNearbyDiff(cm, -1);\n };\n});\n","/**\n * Diff Match and Patch\n * Copyright 2018 The diff-match-patch Authors.\n * https://github.com/google/diff-match-patch\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @fileoverview Computes the difference between two texts to create a patch.\n * Applies the patch onto another text, allowing for errors.\n * @author fraser@google.com (Neil Fraser)\n */\n\n/**\n * Class containing the diff, match and patch methods.\n * @constructor\n */\nvar diff_match_patch = function() {\n\n // Defaults.\n // Redefine these in your program to override the defaults.\n\n // Number of seconds to map a diff before giving up (0 for infinity).\n this.Diff_Timeout = 1.0;\n // Cost of an empty edit operation in terms of edit characters.\n this.Diff_EditCost = 4;\n // At what point is no match declared (0.0 = perfection, 1.0 = very loose).\n this.Match_Threshold = 0.5;\n // How far to search for a match (0 = exact location, 1000+ = broad match).\n // A match this many characters away from the expected location will add\n // 1.0 to the score (0.0 is a perfect match).\n this.Match_Distance = 1000;\n // When deleting a large block of text (over ~64 characters), how close do\n // the contents have to be to match the expected contents. (0.0 = perfection,\n // 1.0 = very loose). Note that Match_Threshold controls how closely the\n // end points of a delete need to match.\n this.Patch_DeleteThreshold = 0.5;\n // Chunk size for context length.\n this.Patch_Margin = 4;\n\n // The number of bits in an int.\n this.Match_MaxBits = 32;\n};\n\n\n// DIFF FUNCTIONS\n\n\n/**\n * The data structure representing a diff is an array of tuples:\n * [[DIFF_DELETE, 'Hello'], [DIFF_INSERT, 'Goodbye'], [DIFF_EQUAL, ' world.']]\n * which means: delete 'Hello', add 'Goodbye' and keep ' world.'\n */\nvar DIFF_DELETE = -1;\nvar DIFF_INSERT = 1;\nvar DIFF_EQUAL = 0;\n\n/**\n * Class representing one diff tuple.\n * ~Attempts to look like a two-element array (which is what this used to be).~\n * Constructor returns an actual two-element array, to allow destructing @JackuB\n * See https://github.com/JackuB/diff-match-patch/issues/14 for details\n * @param {number} op Operation, one of: DIFF_DELETE, DIFF_INSERT, DIFF_EQUAL.\n * @param {string} text Text to be deleted, inserted, or retained.\n * @constructor\n */\ndiff_match_patch.Diff = function(op, text) {\n return [op, text];\n};\n\n/**\n * Find the differences between two texts. Simplifies the problem by stripping\n * any common prefix or suffix off the texts before diffing.\n * @param {string} text1 Old string to be diffed.\n * @param {string} text2 New string to be diffed.\n * @param {boolean=} opt_checklines Optional speedup flag. If present and false,\n * then don't run a line-level diff first to identify the changed areas.\n * Defaults to true, which does a faster, slightly less optimal diff.\n * @param {number=} opt_deadline Optional time when the diff should be complete\n * by. Used internally for recursive calls. Users should set DiffTimeout\n * instead.\n * @return {!Array.} Array of diff tuples.\n */\ndiff_match_patch.prototype.diff_main = function(text1, text2, opt_checklines,\n opt_deadline) {\n // Set a deadline by which time the diff must be complete.\n if (typeof opt_deadline == 'undefined') {\n if (this.Diff_Timeout <= 0) {\n opt_deadline = Number.MAX_VALUE;\n } else {\n opt_deadline = (new Date).getTime() + this.Diff_Timeout * 1000;\n }\n }\n var deadline = opt_deadline;\n\n // Check for null inputs.\n if (text1 == null || text2 == null) {\n throw new Error('Null input. (diff_main)');\n }\n\n // Check for equality (speedup).\n if (text1 == text2) {\n if (text1) {\n return [new diff_match_patch.Diff(DIFF_EQUAL, text1)];\n }\n return [];\n }\n\n if (typeof opt_checklines == 'undefined') {\n opt_checklines = true;\n }\n var checklines = opt_checklines;\n\n // Trim off common prefix (speedup).\n var commonlength = this.diff_commonPrefix(text1, text2);\n var commonprefix = text1.substring(0, commonlength);\n text1 = text1.substring(commonlength);\n text2 = text2.substring(commonlength);\n\n // Trim off common suffix (speedup).\n commonlength = this.diff_commonSuffix(text1, text2);\n var commonsuffix = text1.substring(text1.length - commonlength);\n text1 = text1.substring(0, text1.length - commonlength);\n text2 = text2.substring(0, text2.length - commonlength);\n\n // Compute the diff on the middle block.\n var diffs = this.diff_compute_(text1, text2, checklines, deadline);\n\n // Restore the prefix and suffix.\n if (commonprefix) {\n diffs.unshift(new diff_match_patch.Diff(DIFF_EQUAL, commonprefix));\n }\n if (commonsuffix) {\n diffs.push(new diff_match_patch.Diff(DIFF_EQUAL, commonsuffix));\n }\n this.diff_cleanupMerge(diffs);\n return diffs;\n};\n\n\n/**\n * Find the differences between two texts. Assumes that the texts do not\n * have any common prefix or suffix.\n * @param {string} text1 Old string to be diffed.\n * @param {string} text2 New string to be diffed.\n * @param {boolean} checklines Speedup flag. If false, then don't run a\n * line-level diff first to identify the changed areas.\n * If true, then run a faster, slightly less optimal diff.\n * @param {number} deadline Time when the diff should be complete by.\n * @return {!Array.} Array of diff tuples.\n * @private\n */\ndiff_match_patch.prototype.diff_compute_ = function(text1, text2, checklines,\n deadline) {\n var diffs;\n\n if (!text1) {\n // Just add some text (speedup).\n return [new diff_match_patch.Diff(DIFF_INSERT, text2)];\n }\n\n if (!text2) {\n // Just delete some text (speedup).\n return [new diff_match_patch.Diff(DIFF_DELETE, text1)];\n }\n\n var longtext = text1.length > text2.length ? text1 : text2;\n var shorttext = text1.length > text2.length ? text2 : text1;\n var i = longtext.indexOf(shorttext);\n if (i != -1) {\n // Shorter text is inside the longer text (speedup).\n diffs = [new diff_match_patch.Diff(DIFF_INSERT, longtext.substring(0, i)),\n new diff_match_patch.Diff(DIFF_EQUAL, shorttext),\n new diff_match_patch.Diff(DIFF_INSERT,\n longtext.substring(i + shorttext.length))];\n // Swap insertions for deletions if diff is reversed.\n if (text1.length > text2.length) {\n diffs[0][0] = diffs[2][0] = DIFF_DELETE;\n }\n return diffs;\n }\n\n if (shorttext.length == 1) {\n // Single character string.\n // After the previous speedup, the character can't be an equality.\n return [new diff_match_patch.Diff(DIFF_DELETE, text1),\n new diff_match_patch.Diff(DIFF_INSERT, text2)];\n }\n\n // Check to see if the problem can be split in two.\n var hm = this.diff_halfMatch_(text1, text2);\n if (hm) {\n // A half-match was found, sort out the return data.\n var text1_a = hm[0];\n var text1_b = hm[1];\n var text2_a = hm[2];\n var text2_b = hm[3];\n var mid_common = hm[4];\n // Send both pairs off for separate processing.\n var diffs_a = this.diff_main(text1_a, text2_a, checklines, deadline);\n var diffs_b = this.diff_main(text1_b, text2_b, checklines, deadline);\n // Merge the results.\n return diffs_a.concat([new diff_match_patch.Diff(DIFF_EQUAL, mid_common)],\n diffs_b);\n }\n\n if (checklines && text1.length > 100 && text2.length > 100) {\n return this.diff_lineMode_(text1, text2, deadline);\n }\n\n return this.diff_bisect_(text1, text2, deadline);\n};\n\n\n/**\n * Do a quick line-level diff on both strings, then rediff the parts for\n * greater accuracy.\n * This speedup can produce non-minimal diffs.\n * @param {string} text1 Old string to be diffed.\n * @param {string} text2 New string to be diffed.\n * @param {number} deadline Time when the diff should be complete by.\n * @return {!Array.} Array of diff tuples.\n * @private\n */\ndiff_match_patch.prototype.diff_lineMode_ = function(text1, text2, deadline) {\n // Scan the text on a line-by-line basis first.\n var a = this.diff_linesToChars_(text1, text2);\n text1 = a.chars1;\n text2 = a.chars2;\n var linearray = a.lineArray;\n\n var diffs = this.diff_main(text1, text2, false, deadline);\n\n // Convert the diff back to original text.\n this.diff_charsToLines_(diffs, linearray);\n // Eliminate freak matches (e.g. blank lines)\n this.diff_cleanupSemantic(diffs);\n\n // Rediff any replacement blocks, this time character-by-character.\n // Add a dummy entry at the end.\n diffs.push(new diff_match_patch.Diff(DIFF_EQUAL, ''));\n var pointer = 0;\n var count_delete = 0;\n var count_insert = 0;\n var text_delete = '';\n var text_insert = '';\n while (pointer < diffs.length) {\n switch (diffs[pointer][0]) {\n case DIFF_INSERT:\n count_insert++;\n text_insert += diffs[pointer][1];\n break;\n case DIFF_DELETE:\n count_delete++;\n text_delete += diffs[pointer][1];\n break;\n case DIFF_EQUAL:\n // Upon reaching an equality, check for prior redundancies.\n if (count_delete >= 1 && count_insert >= 1) {\n // Delete the offending records and add the merged ones.\n diffs.splice(pointer - count_delete - count_insert,\n count_delete + count_insert);\n pointer = pointer - count_delete - count_insert;\n var subDiff =\n this.diff_main(text_delete, text_insert, false, deadline);\n for (var j = subDiff.length - 1; j >= 0; j--) {\n diffs.splice(pointer, 0, subDiff[j]);\n }\n pointer = pointer + subDiff.length;\n }\n count_insert = 0;\n count_delete = 0;\n text_delete = '';\n text_insert = '';\n break;\n }\n pointer++;\n }\n diffs.pop(); // Remove the dummy entry at the end.\n\n return diffs;\n};\n\n\n/**\n * Find the 'middle snake' of a diff, split the problem in two\n * and return the recursively constructed diff.\n * See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations.\n * @param {string} text1 Old string to be diffed.\n * @param {string} text2 New string to be diffed.\n * @param {number} deadline Time at which to bail if not yet complete.\n * @return {!Array.} Array of diff tuples.\n * @private\n */\ndiff_match_patch.prototype.diff_bisect_ = function(text1, text2, deadline) {\n // Cache the text lengths to prevent multiple calls.\n var text1_length = text1.length;\n var text2_length = text2.length;\n var max_d = Math.ceil((text1_length + text2_length) / 2);\n var v_offset = max_d;\n var v_length = 2 * max_d;\n var v1 = new Array(v_length);\n var v2 = new Array(v_length);\n // Setting all elements to -1 is faster in Chrome & Firefox than mixing\n // integers and undefined.\n for (var x = 0; x < v_length; x++) {\n v1[x] = -1;\n v2[x] = -1;\n }\n v1[v_offset + 1] = 0;\n v2[v_offset + 1] = 0;\n var delta = text1_length - text2_length;\n // If the total number of characters is odd, then the front path will collide\n // with the reverse path.\n var front = (delta % 2 != 0);\n // Offsets for start and end of k loop.\n // Prevents mapping of space beyond the grid.\n var k1start = 0;\n var k1end = 0;\n var k2start = 0;\n var k2end = 0;\n for (var d = 0; d < max_d; d++) {\n // Bail out if deadline is reached.\n if ((new Date()).getTime() > deadline) {\n break;\n }\n\n // Walk the front path one step.\n for (var k1 = -d + k1start; k1 <= d - k1end; k1 += 2) {\n var k1_offset = v_offset + k1;\n var x1;\n if (k1 == -d || (k1 != d && v1[k1_offset - 1] < v1[k1_offset + 1])) {\n x1 = v1[k1_offset + 1];\n } else {\n x1 = v1[k1_offset - 1] + 1;\n }\n var y1 = x1 - k1;\n while (x1 < text1_length && y1 < text2_length &&\n text1.charAt(x1) == text2.charAt(y1)) {\n x1++;\n y1++;\n }\n v1[k1_offset] = x1;\n if (x1 > text1_length) {\n // Ran off the right of the graph.\n k1end += 2;\n } else if (y1 > text2_length) {\n // Ran off the bottom of the graph.\n k1start += 2;\n } else if (front) {\n var k2_offset = v_offset + delta - k1;\n if (k2_offset >= 0 && k2_offset < v_length && v2[k2_offset] != -1) {\n // Mirror x2 onto top-left coordinate system.\n var x2 = text1_length - v2[k2_offset];\n if (x1 >= x2) {\n // Overlap detected.\n return this.diff_bisectSplit_(text1, text2, x1, y1, deadline);\n }\n }\n }\n }\n\n // Walk the reverse path one step.\n for (var k2 = -d + k2start; k2 <= d - k2end; k2 += 2) {\n var k2_offset = v_offset + k2;\n var x2;\n if (k2 == -d || (k2 != d && v2[k2_offset - 1] < v2[k2_offset + 1])) {\n x2 = v2[k2_offset + 1];\n } else {\n x2 = v2[k2_offset - 1] + 1;\n }\n var y2 = x2 - k2;\n while (x2 < text1_length && y2 < text2_length &&\n text1.charAt(text1_length - x2 - 1) ==\n text2.charAt(text2_length - y2 - 1)) {\n x2++;\n y2++;\n }\n v2[k2_offset] = x2;\n if (x2 > text1_length) {\n // Ran off the left of the graph.\n k2end += 2;\n } else if (y2 > text2_length) {\n // Ran off the top of the graph.\n k2start += 2;\n } else if (!front) {\n var k1_offset = v_offset + delta - k2;\n if (k1_offset >= 0 && k1_offset < v_length && v1[k1_offset] != -1) {\n var x1 = v1[k1_offset];\n var y1 = v_offset + x1 - k1_offset;\n // Mirror x2 onto top-left coordinate system.\n x2 = text1_length - x2;\n if (x1 >= x2) {\n // Overlap detected.\n return this.diff_bisectSplit_(text1, text2, x1, y1, deadline);\n }\n }\n }\n }\n }\n // Diff took too long and hit the deadline or\n // number of diffs equals number of characters, no commonality at all.\n return [new diff_match_patch.Diff(DIFF_DELETE, text1),\n new diff_match_patch.Diff(DIFF_INSERT, text2)];\n};\n\n\n/**\n * Given the location of the 'middle snake', split the diff in two parts\n * and recurse.\n * @param {string} text1 Old string to be diffed.\n * @param {string} text2 New string to be diffed.\n * @param {number} x Index of split point in text1.\n * @param {number} y Index of split point in text2.\n * @param {number} deadline Time at which to bail if not yet complete.\n * @return {!Array.} Array of diff tuples.\n * @private\n */\ndiff_match_patch.prototype.diff_bisectSplit_ = function(text1, text2, x, y,\n deadline) {\n var text1a = text1.substring(0, x);\n var text2a = text2.substring(0, y);\n var text1b = text1.substring(x);\n var text2b = text2.substring(y);\n\n // Compute both diffs serially.\n var diffs = this.diff_main(text1a, text2a, false, deadline);\n var diffsb = this.diff_main(text1b, text2b, false, deadline);\n\n return diffs.concat(diffsb);\n};\n\n\n/**\n * Split two texts into an array of strings. Reduce the texts to a string of\n * hashes where each Unicode character represents one line.\n * @param {string} text1 First string.\n * @param {string} text2 Second string.\n * @return {{chars1: string, chars2: string, lineArray: !Array.}}\n * An object containing the encoded text1, the encoded text2 and\n * the array of unique strings.\n * The zeroth element of the array of unique strings is intentionally blank.\n * @private\n */\ndiff_match_patch.prototype.diff_linesToChars_ = function(text1, text2) {\n var lineArray = []; // e.g. lineArray[4] == 'Hello\\n'\n var lineHash = {}; // e.g. lineHash['Hello\\n'] == 4\n\n // '\\x00' is a valid character, but various debuggers don't like it.\n // So we'll insert a junk entry to avoid generating a null character.\n lineArray[0] = '';\n\n /**\n * Split a text into an array of strings. Reduce the texts to a string of\n * hashes where each Unicode character represents one line.\n * Modifies linearray and linehash through being a closure.\n * @param {string} text String to encode.\n * @return {string} Encoded string.\n * @private\n */\n function diff_linesToCharsMunge_(text) {\n var chars = '';\n // Walk the text, pulling out a substring for each line.\n // text.split('\\n') would would temporarily double our memory footprint.\n // Modifying text would create many large strings to garbage collect.\n var lineStart = 0;\n var lineEnd = -1;\n // Keeping our own length variable is faster than looking it up.\n var lineArrayLength = lineArray.length;\n while (lineEnd < text.length - 1) {\n lineEnd = text.indexOf('\\n', lineStart);\n if (lineEnd == -1) {\n lineEnd = text.length - 1;\n }\n var line = text.substring(lineStart, lineEnd + 1);\n\n if (lineHash.hasOwnProperty ? lineHash.hasOwnProperty(line) :\n (lineHash[line] !== undefined)) {\n chars += String.fromCharCode(lineHash[line]);\n } else {\n if (lineArrayLength == maxLines) {\n // Bail out at 65535 because\n // String.fromCharCode(65536) == String.fromCharCode(0)\n line = text.substring(lineStart);\n lineEnd = text.length;\n }\n chars += String.fromCharCode(lineArrayLength);\n lineHash[line] = lineArrayLength;\n lineArray[lineArrayLength++] = line;\n }\n lineStart = lineEnd + 1;\n }\n return chars;\n }\n // Allocate 2/3rds of the space for text1, the rest for text2.\n var maxLines = 40000;\n var chars1 = diff_linesToCharsMunge_(text1);\n maxLines = 65535;\n var chars2 = diff_linesToCharsMunge_(text2);\n return {chars1: chars1, chars2: chars2, lineArray: lineArray};\n};\n\n\n/**\n * Rehydrate the text in a diff from a string of line hashes to real lines of\n * text.\n * @param {!Array.} diffs Array of diff tuples.\n * @param {!Array.} lineArray Array of unique strings.\n * @private\n */\ndiff_match_patch.prototype.diff_charsToLines_ = function(diffs, lineArray) {\n for (var i = 0; i < diffs.length; i++) {\n var chars = diffs[i][1];\n var text = [];\n for (var j = 0; j < chars.length; j++) {\n text[j] = lineArray[chars.charCodeAt(j)];\n }\n diffs[i][1] = text.join('');\n }\n};\n\n\n/**\n * Determine the common prefix of two strings.\n * @param {string} text1 First string.\n * @param {string} text2 Second string.\n * @return {number} The number of characters common to the start of each\n * string.\n */\ndiff_match_patch.prototype.diff_commonPrefix = function(text1, text2) {\n // Quick check for common null cases.\n if (!text1 || !text2 || text1.charAt(0) != text2.charAt(0)) {\n return 0;\n }\n // Binary search.\n // Performance analysis: https://neil.fraser.name/news/2007/10/09/\n var pointermin = 0;\n var pointermax = Math.min(text1.length, text2.length);\n var pointermid = pointermax;\n var pointerstart = 0;\n while (pointermin < pointermid) {\n if (text1.substring(pointerstart, pointermid) ==\n text2.substring(pointerstart, pointermid)) {\n pointermin = pointermid;\n pointerstart = pointermin;\n } else {\n pointermax = pointermid;\n }\n pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin);\n }\n return pointermid;\n};\n\n\n/**\n * Determine the common suffix of two strings.\n * @param {string} text1 First string.\n * @param {string} text2 Second string.\n * @return {number} The number of characters common to the end of each string.\n */\ndiff_match_patch.prototype.diff_commonSuffix = function(text1, text2) {\n // Quick check for common null cases.\n if (!text1 || !text2 ||\n text1.charAt(text1.length - 1) != text2.charAt(text2.length - 1)) {\n return 0;\n }\n // Binary search.\n // Performance analysis: https://neil.fraser.name/news/2007/10/09/\n var pointermin = 0;\n var pointermax = Math.min(text1.length, text2.length);\n var pointermid = pointermax;\n var pointerend = 0;\n while (pointermin < pointermid) {\n if (text1.substring(text1.length - pointermid, text1.length - pointerend) ==\n text2.substring(text2.length - pointermid, text2.length - pointerend)) {\n pointermin = pointermid;\n pointerend = pointermin;\n } else {\n pointermax = pointermid;\n }\n pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin);\n }\n return pointermid;\n};\n\n\n/**\n * Determine if the suffix of one string is the prefix of another.\n * @param {string} text1 First string.\n * @param {string} text2 Second string.\n * @return {number} The number of characters common to the end of the first\n * string and the start of the second string.\n * @private\n */\ndiff_match_patch.prototype.diff_commonOverlap_ = function(text1, text2) {\n // Cache the text lengths to prevent multiple calls.\n var text1_length = text1.length;\n var text2_length = text2.length;\n // Eliminate the null case.\n if (text1_length == 0 || text2_length == 0) {\n return 0;\n }\n // Truncate the longer string.\n if (text1_length > text2_length) {\n text1 = text1.substring(text1_length - text2_length);\n } else if (text1_length < text2_length) {\n text2 = text2.substring(0, text1_length);\n }\n var text_length = Math.min(text1_length, text2_length);\n // Quick check for the worst case.\n if (text1 == text2) {\n return text_length;\n }\n\n // Start by looking for a single character match\n // and increase length until no match is found.\n // Performance analysis: https://neil.fraser.name/news/2010/11/04/\n var best = 0;\n var length = 1;\n while (true) {\n var pattern = text1.substring(text_length - length);\n var found = text2.indexOf(pattern);\n if (found == -1) {\n return best;\n }\n length += found;\n if (found == 0 || text1.substring(text_length - length) ==\n text2.substring(0, length)) {\n best = length;\n length++;\n }\n }\n};\n\n\n/**\n * Do the two texts share a substring which is at least half the length of the\n * longer text?\n * This speedup can produce non-minimal diffs.\n * @param {string} text1 First string.\n * @param {string} text2 Second string.\n * @return {Array.} Five element Array, containing the prefix of\n * text1, the suffix of text1, the prefix of text2, the suffix of\n * text2 and the common middle. Or null if there was no match.\n * @private\n */\ndiff_match_patch.prototype.diff_halfMatch_ = function(text1, text2) {\n if (this.Diff_Timeout <= 0) {\n // Don't risk returning a non-optimal diff if we have unlimited time.\n return null;\n }\n var longtext = text1.length > text2.length ? text1 : text2;\n var shorttext = text1.length > text2.length ? text2 : text1;\n if (longtext.length < 4 || shorttext.length * 2 < longtext.length) {\n return null; // Pointless.\n }\n var dmp = this; // 'this' becomes 'window' in a closure.\n\n /**\n * Does a substring of shorttext exist within longtext such that the substring\n * is at least half the length of longtext?\n * Closure, but does not reference any external variables.\n * @param {string} longtext Longer string.\n * @param {string} shorttext Shorter string.\n * @param {number} i Start index of quarter length substring within longtext.\n * @return {Array.} Five element Array, containing the prefix of\n * longtext, the suffix of longtext, the prefix of shorttext, the suffix\n * of shorttext and the common middle. Or null if there was no match.\n * @private\n */\n function diff_halfMatchI_(longtext, shorttext, i) {\n // Start with a 1/4 length substring at position i as a seed.\n var seed = longtext.substring(i, i + Math.floor(longtext.length / 4));\n var j = -1;\n var best_common = '';\n var best_longtext_a, best_longtext_b, best_shorttext_a, best_shorttext_b;\n while ((j = shorttext.indexOf(seed, j + 1)) != -1) {\n var prefixLength = dmp.diff_commonPrefix(longtext.substring(i),\n shorttext.substring(j));\n var suffixLength = dmp.diff_commonSuffix(longtext.substring(0, i),\n shorttext.substring(0, j));\n if (best_common.length < suffixLength + prefixLength) {\n best_common = shorttext.substring(j - suffixLength, j) +\n shorttext.substring(j, j + prefixLength);\n best_longtext_a = longtext.substring(0, i - suffixLength);\n best_longtext_b = longtext.substring(i + prefixLength);\n best_shorttext_a = shorttext.substring(0, j - suffixLength);\n best_shorttext_b = shorttext.substring(j + prefixLength);\n }\n }\n if (best_common.length * 2 >= longtext.length) {\n return [best_longtext_a, best_longtext_b,\n best_shorttext_a, best_shorttext_b, best_common];\n } else {\n return null;\n }\n }\n\n // First check if the second quarter is the seed for a half-match.\n var hm1 = diff_halfMatchI_(longtext, shorttext,\n Math.ceil(longtext.length / 4));\n // Check again based on the third quarter.\n var hm2 = diff_halfMatchI_(longtext, shorttext,\n Math.ceil(longtext.length / 2));\n var hm;\n if (!hm1 && !hm2) {\n return null;\n } else if (!hm2) {\n hm = hm1;\n } else if (!hm1) {\n hm = hm2;\n } else {\n // Both matched. Select the longest.\n hm = hm1[4].length > hm2[4].length ? hm1 : hm2;\n }\n\n // A half-match was found, sort out the return data.\n var text1_a, text1_b, text2_a, text2_b;\n if (text1.length > text2.length) {\n text1_a = hm[0];\n text1_b = hm[1];\n text2_a = hm[2];\n text2_b = hm[3];\n } else {\n text2_a = hm[0];\n text2_b = hm[1];\n text1_a = hm[2];\n text1_b = hm[3];\n }\n var mid_common = hm[4];\n return [text1_a, text1_b, text2_a, text2_b, mid_common];\n};\n\n\n/**\n * Reduce the number of edits by eliminating semantically trivial equalities.\n * @param {!Array.} diffs Array of diff tuples.\n */\ndiff_match_patch.prototype.diff_cleanupSemantic = function(diffs) {\n var changes = false;\n var equalities = []; // Stack of indices where equalities are found.\n var equalitiesLength = 0; // Keeping our own length var is faster in JS.\n /** @type {?string} */\n var lastEquality = null;\n // Always equal to diffs[equalities[equalitiesLength - 1]][1]\n var pointer = 0; // Index of current position.\n // Number of characters that changed prior to the equality.\n var length_insertions1 = 0;\n var length_deletions1 = 0;\n // Number of characters that changed after the equality.\n var length_insertions2 = 0;\n var length_deletions2 = 0;\n while (pointer < diffs.length) {\n if (diffs[pointer][0] == DIFF_EQUAL) { // Equality found.\n equalities[equalitiesLength++] = pointer;\n length_insertions1 = length_insertions2;\n length_deletions1 = length_deletions2;\n length_insertions2 = 0;\n length_deletions2 = 0;\n lastEquality = diffs[pointer][1];\n } else { // An insertion or deletion.\n if (diffs[pointer][0] == DIFF_INSERT) {\n length_insertions2 += diffs[pointer][1].length;\n } else {\n length_deletions2 += diffs[pointer][1].length;\n }\n // Eliminate an equality that is smaller or equal to the edits on both\n // sides of it.\n if (lastEquality && (lastEquality.length <=\n Math.max(length_insertions1, length_deletions1)) &&\n (lastEquality.length <= Math.max(length_insertions2,\n length_deletions2))) {\n // Duplicate record.\n diffs.splice(equalities[equalitiesLength - 1], 0,\n new diff_match_patch.Diff(DIFF_DELETE, lastEquality));\n // Change second copy to insert.\n diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT;\n // Throw away the equality we just deleted.\n equalitiesLength--;\n // Throw away the previous equality (it needs to be reevaluated).\n equalitiesLength--;\n pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1;\n length_insertions1 = 0; // Reset the counters.\n length_deletions1 = 0;\n length_insertions2 = 0;\n length_deletions2 = 0;\n lastEquality = null;\n changes = true;\n }\n }\n pointer++;\n }\n\n // Normalize the diff.\n if (changes) {\n this.diff_cleanupMerge(diffs);\n }\n this.diff_cleanupSemanticLossless(diffs);\n\n // Find any overlaps between deletions and insertions.\n // e.g: abcxxxxxxdef\n // -> abcxxxdef\n // e.g: xxxabcdefxxx\n // -> defxxxabc\n // Only extract an overlap if it is as big as the edit ahead or behind it.\n pointer = 1;\n while (pointer < diffs.length) {\n if (diffs[pointer - 1][0] == DIFF_DELETE &&\n diffs[pointer][0] == DIFF_INSERT) {\n var deletion = diffs[pointer - 1][1];\n var insertion = diffs[pointer][1];\n var overlap_length1 = this.diff_commonOverlap_(deletion, insertion);\n var overlap_length2 = this.diff_commonOverlap_(insertion, deletion);\n if (overlap_length1 >= overlap_length2) {\n if (overlap_length1 >= deletion.length / 2 ||\n overlap_length1 >= insertion.length / 2) {\n // Overlap found. Insert an equality and trim the surrounding edits.\n diffs.splice(pointer, 0, new diff_match_patch.Diff(DIFF_EQUAL,\n insertion.substring(0, overlap_length1)));\n diffs[pointer - 1][1] =\n deletion.substring(0, deletion.length - overlap_length1);\n diffs[pointer + 1][1] = insertion.substring(overlap_length1);\n pointer++;\n }\n } else {\n if (overlap_length2 >= deletion.length / 2 ||\n overlap_length2 >= insertion.length / 2) {\n // Reverse overlap found.\n // Insert an equality and swap and trim the surrounding edits.\n diffs.splice(pointer, 0, new diff_match_patch.Diff(DIFF_EQUAL,\n deletion.substring(0, overlap_length2)));\n diffs[pointer - 1][0] = DIFF_INSERT;\n diffs[pointer - 1][1] =\n insertion.substring(0, insertion.length - overlap_length2);\n diffs[pointer + 1][0] = DIFF_DELETE;\n diffs[pointer + 1][1] =\n deletion.substring(overlap_length2);\n pointer++;\n }\n }\n pointer++;\n }\n pointer++;\n }\n};\n\n\n/**\n * Look for single edits surrounded on both sides by equalities\n * which can be shifted sideways to align the edit to a word boundary.\n * e.g: The cat came. -> The cat came.\n * @param {!Array.} diffs Array of diff tuples.\n */\ndiff_match_patch.prototype.diff_cleanupSemanticLossless = function(diffs) {\n /**\n * Given two strings, compute a score representing whether the internal\n * boundary falls on logical boundaries.\n * Scores range from 6 (best) to 0 (worst).\n * Closure, but does not reference any external variables.\n * @param {string} one First string.\n * @param {string} two Second string.\n * @return {number} The score.\n * @private\n */\n function diff_cleanupSemanticScore_(one, two) {\n if (!one || !two) {\n // Edges are the best.\n return 6;\n }\n\n // Each port of this function behaves slightly differently due to\n // subtle differences in each language's definition of things like\n // 'whitespace'. Since this function's purpose is largely cosmetic,\n // the choice has been made to use each language's native features\n // rather than force total conformity.\n var char1 = one.charAt(one.length - 1);\n var char2 = two.charAt(0);\n var nonAlphaNumeric1 = char1.match(diff_match_patch.nonAlphaNumericRegex_);\n var nonAlphaNumeric2 = char2.match(diff_match_patch.nonAlphaNumericRegex_);\n var whitespace1 = nonAlphaNumeric1 &&\n char1.match(diff_match_patch.whitespaceRegex_);\n var whitespace2 = nonAlphaNumeric2 &&\n char2.match(diff_match_patch.whitespaceRegex_);\n var lineBreak1 = whitespace1 &&\n char1.match(diff_match_patch.linebreakRegex_);\n var lineBreak2 = whitespace2 &&\n char2.match(diff_match_patch.linebreakRegex_);\n var blankLine1 = lineBreak1 &&\n one.match(diff_match_patch.blanklineEndRegex_);\n var blankLine2 = lineBreak2 &&\n two.match(diff_match_patch.blanklineStartRegex_);\n\n if (blankLine1 || blankLine2) {\n // Five points for blank lines.\n return 5;\n } else if (lineBreak1 || lineBreak2) {\n // Four points for line breaks.\n return 4;\n } else if (nonAlphaNumeric1 && !whitespace1 && whitespace2) {\n // Three points for end of sentences.\n return 3;\n } else if (whitespace1 || whitespace2) {\n // Two points for whitespace.\n return 2;\n } else if (nonAlphaNumeric1 || nonAlphaNumeric2) {\n // One point for non-alphanumeric.\n return 1;\n }\n return 0;\n }\n\n var pointer = 1;\n // Intentionally ignore the first and last element (don't need checking).\n while (pointer < diffs.length - 1) {\n if (diffs[pointer - 1][0] == DIFF_EQUAL &&\n diffs[pointer + 1][0] == DIFF_EQUAL) {\n // This is a single edit surrounded by equalities.\n var equality1 = diffs[pointer - 1][1];\n var edit = diffs[pointer][1];\n var equality2 = diffs[pointer + 1][1];\n\n // First, shift the edit as far left as possible.\n var commonOffset = this.diff_commonSuffix(equality1, edit);\n if (commonOffset) {\n var commonString = edit.substring(edit.length - commonOffset);\n equality1 = equality1.substring(0, equality1.length - commonOffset);\n edit = commonString + edit.substring(0, edit.length - commonOffset);\n equality2 = commonString + equality2;\n }\n\n // Second, step character by character right, looking for the best fit.\n var bestEquality1 = equality1;\n var bestEdit = edit;\n var bestEquality2 = equality2;\n var bestScore = diff_cleanupSemanticScore_(equality1, edit) +\n diff_cleanupSemanticScore_(edit, equality2);\n while (edit.charAt(0) === equality2.charAt(0)) {\n equality1 += edit.charAt(0);\n edit = edit.substring(1) + equality2.charAt(0);\n equality2 = equality2.substring(1);\n var score = diff_cleanupSemanticScore_(equality1, edit) +\n diff_cleanupSemanticScore_(edit, equality2);\n // The >= encourages trailing rather than leading whitespace on edits.\n if (score >= bestScore) {\n bestScore = score;\n bestEquality1 = equality1;\n bestEdit = edit;\n bestEquality2 = equality2;\n }\n }\n\n if (diffs[pointer - 1][1] != bestEquality1) {\n // We have an improvement, save it back to the diff.\n if (bestEquality1) {\n diffs[pointer - 1][1] = bestEquality1;\n } else {\n diffs.splice(pointer - 1, 1);\n pointer--;\n }\n diffs[pointer][1] = bestEdit;\n if (bestEquality2) {\n diffs[pointer + 1][1] = bestEquality2;\n } else {\n diffs.splice(pointer + 1, 1);\n pointer--;\n }\n }\n }\n pointer++;\n }\n};\n\n// Define some regex patterns for matching boundaries.\ndiff_match_patch.nonAlphaNumericRegex_ = /[^a-zA-Z0-9]/;\ndiff_match_patch.whitespaceRegex_ = /\\s/;\ndiff_match_patch.linebreakRegex_ = /[\\r\\n]/;\ndiff_match_patch.blanklineEndRegex_ = /\\n\\r?\\n$/;\ndiff_match_patch.blanklineStartRegex_ = /^\\r?\\n\\r?\\n/;\n\n/**\n * Reduce the number of edits by eliminating operationally trivial equalities.\n * @param {!Array.} diffs Array of diff tuples.\n */\ndiff_match_patch.prototype.diff_cleanupEfficiency = function(diffs) {\n var changes = false;\n var equalities = []; // Stack of indices where equalities are found.\n var equalitiesLength = 0; // Keeping our own length var is faster in JS.\n /** @type {?string} */\n var lastEquality = null;\n // Always equal to diffs[equalities[equalitiesLength - 1]][1]\n var pointer = 0; // Index of current position.\n // Is there an insertion operation before the last equality.\n var pre_ins = false;\n // Is there a deletion operation before the last equality.\n var pre_del = false;\n // Is there an insertion operation after the last equality.\n var post_ins = false;\n // Is there a deletion operation after the last equality.\n var post_del = false;\n while (pointer < diffs.length) {\n if (diffs[pointer][0] == DIFF_EQUAL) { // Equality found.\n if (diffs[pointer][1].length < this.Diff_EditCost &&\n (post_ins || post_del)) {\n // Candidate found.\n equalities[equalitiesLength++] = pointer;\n pre_ins = post_ins;\n pre_del = post_del;\n lastEquality = diffs[pointer][1];\n } else {\n // Not a candidate, and can never become one.\n equalitiesLength = 0;\n lastEquality = null;\n }\n post_ins = post_del = false;\n } else { // An insertion or deletion.\n if (diffs[pointer][0] == DIFF_DELETE) {\n post_del = true;\n } else {\n post_ins = true;\n }\n /*\n * Five types to be split:\n * ABXYCD\n * AXCD\n * ABXC\n * AXCD\n * ABXC\n */\n if (lastEquality && ((pre_ins && pre_del && post_ins && post_del) ||\n ((lastEquality.length < this.Diff_EditCost / 2) &&\n (pre_ins + pre_del + post_ins + post_del) == 3))) {\n // Duplicate record.\n diffs.splice(equalities[equalitiesLength - 1], 0,\n new diff_match_patch.Diff(DIFF_DELETE, lastEquality));\n // Change second copy to insert.\n diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT;\n equalitiesLength--; // Throw away the equality we just deleted;\n lastEquality = null;\n if (pre_ins && pre_del) {\n // No changes made which could affect previous entry, keep going.\n post_ins = post_del = true;\n equalitiesLength = 0;\n } else {\n equalitiesLength--; // Throw away the previous equality.\n pointer = equalitiesLength > 0 ?\n equalities[equalitiesLength - 1] : -1;\n post_ins = post_del = false;\n }\n changes = true;\n }\n }\n pointer++;\n }\n\n if (changes) {\n this.diff_cleanupMerge(diffs);\n }\n};\n\n\n/**\n * Reorder and merge like edit sections. Merge equalities.\n * Any edit section can move as long as it doesn't cross an equality.\n * @param {!Array.} diffs Array of diff tuples.\n */\ndiff_match_patch.prototype.diff_cleanupMerge = function(diffs) {\n // Add a dummy entry at the end.\n diffs.push(new diff_match_patch.Diff(DIFF_EQUAL, ''));\n var pointer = 0;\n var count_delete = 0;\n var count_insert = 0;\n var text_delete = '';\n var text_insert = '';\n var commonlength;\n while (pointer < diffs.length) {\n switch (diffs[pointer][0]) {\n case DIFF_INSERT:\n count_insert++;\n text_insert += diffs[pointer][1];\n pointer++;\n break;\n case DIFF_DELETE:\n count_delete++;\n text_delete += diffs[pointer][1];\n pointer++;\n break;\n case DIFF_EQUAL:\n // Upon reaching an equality, check for prior redundancies.\n if (count_delete + count_insert > 1) {\n if (count_delete !== 0 && count_insert !== 0) {\n // Factor out any common prefixies.\n commonlength = this.diff_commonPrefix(text_insert, text_delete);\n if (commonlength !== 0) {\n if ((pointer - count_delete - count_insert) > 0 &&\n diffs[pointer - count_delete - count_insert - 1][0] ==\n DIFF_EQUAL) {\n diffs[pointer - count_delete - count_insert - 1][1] +=\n text_insert.substring(0, commonlength);\n } else {\n diffs.splice(0, 0, new diff_match_patch.Diff(DIFF_EQUAL,\n text_insert.substring(0, commonlength)));\n pointer++;\n }\n text_insert = text_insert.substring(commonlength);\n text_delete = text_delete.substring(commonlength);\n }\n // Factor out any common suffixies.\n commonlength = this.diff_commonSuffix(text_insert, text_delete);\n if (commonlength !== 0) {\n diffs[pointer][1] = text_insert.substring(text_insert.length -\n commonlength) + diffs[pointer][1];\n text_insert = text_insert.substring(0, text_insert.length -\n commonlength);\n text_delete = text_delete.substring(0, text_delete.length -\n commonlength);\n }\n }\n // Delete the offending records and add the merged ones.\n pointer -= count_delete + count_insert;\n diffs.splice(pointer, count_delete + count_insert);\n if (text_delete.length) {\n diffs.splice(pointer, 0,\n new diff_match_patch.Diff(DIFF_DELETE, text_delete));\n pointer++;\n }\n if (text_insert.length) {\n diffs.splice(pointer, 0,\n new diff_match_patch.Diff(DIFF_INSERT, text_insert));\n pointer++;\n }\n pointer++;\n } else if (pointer !== 0 && diffs[pointer - 1][0] == DIFF_EQUAL) {\n // Merge this equality with the previous one.\n diffs[pointer - 1][1] += diffs[pointer][1];\n diffs.splice(pointer, 1);\n } else {\n pointer++;\n }\n count_insert = 0;\n count_delete = 0;\n text_delete = '';\n text_insert = '';\n break;\n }\n }\n if (diffs[diffs.length - 1][1] === '') {\n diffs.pop(); // Remove the dummy entry at the end.\n }\n\n // Second pass: look for single edits surrounded on both sides by equalities\n // which can be shifted sideways to eliminate an equality.\n // e.g: ABAC -> ABAC\n var changes = false;\n pointer = 1;\n // Intentionally ignore the first and last element (don't need checking).\n while (pointer < diffs.length - 1) {\n if (diffs[pointer - 1][0] == DIFF_EQUAL &&\n diffs[pointer + 1][0] == DIFF_EQUAL) {\n // This is a single edit surrounded by equalities.\n if (diffs[pointer][1].substring(diffs[pointer][1].length -\n diffs[pointer - 1][1].length) == diffs[pointer - 1][1]) {\n // Shift the edit over the previous equality.\n diffs[pointer][1] = diffs[pointer - 1][1] +\n diffs[pointer][1].substring(0, diffs[pointer][1].length -\n diffs[pointer - 1][1].length);\n diffs[pointer + 1][1] = diffs[pointer - 1][1] + diffs[pointer + 1][1];\n diffs.splice(pointer - 1, 1);\n changes = true;\n } else if (diffs[pointer][1].substring(0, diffs[pointer + 1][1].length) ==\n diffs[pointer + 1][1]) {\n // Shift the edit over the next equality.\n diffs[pointer - 1][1] += diffs[pointer + 1][1];\n diffs[pointer][1] =\n diffs[pointer][1].substring(diffs[pointer + 1][1].length) +\n diffs[pointer + 1][1];\n diffs.splice(pointer + 1, 1);\n changes = true;\n }\n }\n pointer++;\n }\n // If shifts were made, the diff needs reordering and another shift sweep.\n if (changes) {\n this.diff_cleanupMerge(diffs);\n }\n};\n\n\n/**\n * loc is a location in text1, compute and return the equivalent location in\n * text2.\n * e.g. 'The cat' vs 'The big cat', 1->1, 5->8\n * @param {!Array.} diffs Array of diff tuples.\n * @param {number} loc Location within text1.\n * @return {number} Location within text2.\n */\ndiff_match_patch.prototype.diff_xIndex = function(diffs, loc) {\n var chars1 = 0;\n var chars2 = 0;\n var last_chars1 = 0;\n var last_chars2 = 0;\n var x;\n for (x = 0; x < diffs.length; x++) {\n if (diffs[x][0] !== DIFF_INSERT) { // Equality or deletion.\n chars1 += diffs[x][1].length;\n }\n if (diffs[x][0] !== DIFF_DELETE) { // Equality or insertion.\n chars2 += diffs[x][1].length;\n }\n if (chars1 > loc) { // Overshot the location.\n break;\n }\n last_chars1 = chars1;\n last_chars2 = chars2;\n }\n // Was the location was deleted?\n if (diffs.length != x && diffs[x][0] === DIFF_DELETE) {\n return last_chars2;\n }\n // Add the remaining character length.\n return last_chars2 + (loc - last_chars1);\n};\n\n\n/**\n * Convert a diff array into a pretty HTML report.\n * @param {!Array.} diffs Array of diff tuples.\n * @return {string} HTML representation.\n */\ndiff_match_patch.prototype.diff_prettyHtml = function(diffs) {\n var html = [];\n var pattern_amp = /&/g;\n var pattern_lt = //g;\n var pattern_para = /\\n/g;\n for (var x = 0; x < diffs.length; x++) {\n var op = diffs[x][0]; // Operation (insert, delete, equal)\n var data = diffs[x][1]; // Text of change.\n var text = data.replace(pattern_amp, '&').replace(pattern_lt, '<')\n .replace(pattern_gt, '>').replace(pattern_para, '¶
');\n switch (op) {\n case DIFF_INSERT:\n html[x] = '' + text + '';\n break;\n case DIFF_DELETE:\n html[x] = '' + text + '';\n break;\n case DIFF_EQUAL:\n html[x] = '' + text + '';\n break;\n }\n }\n return html.join('');\n};\n\n\n/**\n * Compute and return the source text (all equalities and deletions).\n * @param {!Array.} diffs Array of diff tuples.\n * @return {string} Source text.\n */\ndiff_match_patch.prototype.diff_text1 = function(diffs) {\n var text = [];\n for (var x = 0; x < diffs.length; x++) {\n if (diffs[x][0] !== DIFF_INSERT) {\n text[x] = diffs[x][1];\n }\n }\n return text.join('');\n};\n\n\n/**\n * Compute and return the destination text (all equalities and insertions).\n * @param {!Array.} diffs Array of diff tuples.\n * @return {string} Destination text.\n */\ndiff_match_patch.prototype.diff_text2 = function(diffs) {\n var text = [];\n for (var x = 0; x < diffs.length; x++) {\n if (diffs[x][0] !== DIFF_DELETE) {\n text[x] = diffs[x][1];\n }\n }\n return text.join('');\n};\n\n\n/**\n * Compute the Levenshtein distance; the number of inserted, deleted or\n * substituted characters.\n * @param {!Array.} diffs Array of diff tuples.\n * @return {number} Number of changes.\n */\ndiff_match_patch.prototype.diff_levenshtein = function(diffs) {\n var levenshtein = 0;\n var insertions = 0;\n var deletions = 0;\n for (var x = 0; x < diffs.length; x++) {\n var op = diffs[x][0];\n var data = diffs[x][1];\n switch (op) {\n case DIFF_INSERT:\n insertions += data.length;\n break;\n case DIFF_DELETE:\n deletions += data.length;\n break;\n case DIFF_EQUAL:\n // A deletion and an insertion is one substitution.\n levenshtein += Math.max(insertions, deletions);\n insertions = 0;\n deletions = 0;\n break;\n }\n }\n levenshtein += Math.max(insertions, deletions);\n return levenshtein;\n};\n\n\n/**\n * Crush the diff into an encoded string which describes the operations\n * required to transform text1 into text2.\n * E.g. =3\\t-2\\t+ing -> Keep 3 chars, delete 2 chars, insert 'ing'.\n * Operations are tab-separated. Inserted text is escaped using %xx notation.\n * @param {!Array.} diffs Array of diff tuples.\n * @return {string} Delta text.\n */\ndiff_match_patch.prototype.diff_toDelta = function(diffs) {\n var text = [];\n for (var x = 0; x < diffs.length; x++) {\n switch (diffs[x][0]) {\n case DIFF_INSERT:\n text[x] = '+' + encodeURI(diffs[x][1]);\n break;\n case DIFF_DELETE:\n text[x] = '-' + diffs[x][1].length;\n break;\n case DIFF_EQUAL:\n text[x] = '=' + diffs[x][1].length;\n break;\n }\n }\n return text.join('\\t').replace(/%20/g, ' ');\n};\n\n\n/**\n * Given the original text1, and an encoded string which describes the\n * operations required to transform text1 into text2, compute the full diff.\n * @param {string} text1 Source string for the diff.\n * @param {string} delta Delta text.\n * @return {!Array.} Array of diff tuples.\n * @throws {!Error} If invalid input.\n */\ndiff_match_patch.prototype.diff_fromDelta = function(text1, delta) {\n var diffs = [];\n var diffsLength = 0; // Keeping our own length var is faster in JS.\n var pointer = 0; // Cursor in text1\n var tokens = delta.split(/\\t/g);\n for (var x = 0; x < tokens.length; x++) {\n // Each token begins with a one character parameter which specifies the\n // operation of this token (delete, insert, equality).\n var param = tokens[x].substring(1);\n switch (tokens[x].charAt(0)) {\n case '+':\n try {\n diffs[diffsLength++] =\n new diff_match_patch.Diff(DIFF_INSERT, decodeURI(param));\n } catch (ex) {\n // Malformed URI sequence.\n throw new Error('Illegal escape in diff_fromDelta: ' + param);\n }\n break;\n case '-':\n // Fall through.\n case '=':\n var n = parseInt(param, 10);\n if (isNaN(n) || n < 0) {\n throw new Error('Invalid number in diff_fromDelta: ' + param);\n }\n var text = text1.substring(pointer, pointer += n);\n if (tokens[x].charAt(0) == '=') {\n diffs[diffsLength++] = new diff_match_patch.Diff(DIFF_EQUAL, text);\n } else {\n diffs[diffsLength++] = new diff_match_patch.Diff(DIFF_DELETE, text);\n }\n break;\n default:\n // Blank tokens are ok (from a trailing \\t).\n // Anything else is an error.\n if (tokens[x]) {\n throw new Error('Invalid diff operation in diff_fromDelta: ' +\n tokens[x]);\n }\n }\n }\n if (pointer != text1.length) {\n throw new Error('Delta length (' + pointer +\n ') does not equal source text length (' + text1.length + ').');\n }\n return diffs;\n};\n\n\n// MATCH FUNCTIONS\n\n\n/**\n * Locate the best instance of 'pattern' in 'text' near 'loc'.\n * @param {string} text The text to search.\n * @param {string} pattern The pattern to search for.\n * @param {number} loc The location to search around.\n * @return {number} Best match index or -1.\n */\ndiff_match_patch.prototype.match_main = function(text, pattern, loc) {\n // Check for null inputs.\n if (text == null || pattern == null || loc == null) {\n throw new Error('Null input. (match_main)');\n }\n\n loc = Math.max(0, Math.min(loc, text.length));\n if (text == pattern) {\n // Shortcut (potentially not guaranteed by the algorithm)\n return 0;\n } else if (!text.length) {\n // Nothing to match.\n return -1;\n } else if (text.substring(loc, loc + pattern.length) == pattern) {\n // Perfect match at the perfect spot! (Includes case of null pattern)\n return loc;\n } else {\n // Do a fuzzy compare.\n return this.match_bitap_(text, pattern, loc);\n }\n};\n\n\n/**\n * Locate the best instance of 'pattern' in 'text' near 'loc' using the\n * Bitap algorithm.\n * @param {string} text The text to search.\n * @param {string} pattern The pattern to search for.\n * @param {number} loc The location to search around.\n * @return {number} Best match index or -1.\n * @private\n */\ndiff_match_patch.prototype.match_bitap_ = function(text, pattern, loc) {\n if (pattern.length > this.Match_MaxBits) {\n throw new Error('Pattern too long for this browser.');\n }\n\n // Initialise the alphabet.\n var s = this.match_alphabet_(pattern);\n\n var dmp = this; // 'this' becomes 'window' in a closure.\n\n /**\n * Compute and return the score for a match with e errors and x location.\n * Accesses loc and pattern through being a closure.\n * @param {number} e Number of errors in match.\n * @param {number} x Location of match.\n * @return {number} Overall score for match (0.0 = good, 1.0 = bad).\n * @private\n */\n function match_bitapScore_(e, x) {\n var accuracy = e / pattern.length;\n var proximity = Math.abs(loc - x);\n if (!dmp.Match_Distance) {\n // Dodge divide by zero error.\n return proximity ? 1.0 : accuracy;\n }\n return accuracy + (proximity / dmp.Match_Distance);\n }\n\n // Highest score beyond which we give up.\n var score_threshold = this.Match_Threshold;\n // Is there a nearby exact match? (speedup)\n var best_loc = text.indexOf(pattern, loc);\n if (best_loc != -1) {\n score_threshold = Math.min(match_bitapScore_(0, best_loc), score_threshold);\n // What about in the other direction? (speedup)\n best_loc = text.lastIndexOf(pattern, loc + pattern.length);\n if (best_loc != -1) {\n score_threshold =\n Math.min(match_bitapScore_(0, best_loc), score_threshold);\n }\n }\n\n // Initialise the bit arrays.\n var matchmask = 1 << (pattern.length - 1);\n best_loc = -1;\n\n var bin_min, bin_mid;\n var bin_max = pattern.length + text.length;\n var last_rd;\n for (var d = 0; d < pattern.length; d++) {\n // Scan for the best match; each iteration allows for one more error.\n // Run a binary search to determine how far from 'loc' we can stray at this\n // error level.\n bin_min = 0;\n bin_mid = bin_max;\n while (bin_min < bin_mid) {\n if (match_bitapScore_(d, loc + bin_mid) <= score_threshold) {\n bin_min = bin_mid;\n } else {\n bin_max = bin_mid;\n }\n bin_mid = Math.floor((bin_max - bin_min) / 2 + bin_min);\n }\n // Use the result from this iteration as the maximum for the next.\n bin_max = bin_mid;\n var start = Math.max(1, loc - bin_mid + 1);\n var finish = Math.min(loc + bin_mid, text.length) + pattern.length;\n\n var rd = Array(finish + 2);\n rd[finish + 1] = (1 << d) - 1;\n for (var j = finish; j >= start; j--) {\n // The alphabet (s) is a sparse hash, so the following line generates\n // warnings.\n var charMatch = s[text.charAt(j - 1)];\n if (d === 0) { // First pass: exact match.\n rd[j] = ((rd[j + 1] << 1) | 1) & charMatch;\n } else { // Subsequent passes: fuzzy match.\n rd[j] = (((rd[j + 1] << 1) | 1) & charMatch) |\n (((last_rd[j + 1] | last_rd[j]) << 1) | 1) |\n last_rd[j + 1];\n }\n if (rd[j] & matchmask) {\n var score = match_bitapScore_(d, j - 1);\n // This match will almost certainly be better than any existing match.\n // But check anyway.\n if (score <= score_threshold) {\n // Told you so.\n score_threshold = score;\n best_loc = j - 1;\n if (best_loc > loc) {\n // When passing loc, don't exceed our current distance from loc.\n start = Math.max(1, 2 * loc - best_loc);\n } else {\n // Already passed loc, downhill from here on in.\n break;\n }\n }\n }\n }\n // No hope for a (better) match at greater error levels.\n if (match_bitapScore_(d + 1, loc) > score_threshold) {\n break;\n }\n last_rd = rd;\n }\n return best_loc;\n};\n\n\n/**\n * Initialise the alphabet for the Bitap algorithm.\n * @param {string} pattern The text to encode.\n * @return {!Object} Hash of character locations.\n * @private\n */\ndiff_match_patch.prototype.match_alphabet_ = function(pattern) {\n var s = {};\n for (var i = 0; i < pattern.length; i++) {\n s[pattern.charAt(i)] = 0;\n }\n for (var i = 0; i < pattern.length; i++) {\n s[pattern.charAt(i)] |= 1 << (pattern.length - i - 1);\n }\n return s;\n};\n\n\n// PATCH FUNCTIONS\n\n\n/**\n * Increase the context until it is unique,\n * but don't let the pattern expand beyond Match_MaxBits.\n * @param {!diff_match_patch.patch_obj} patch The patch to grow.\n * @param {string} text Source text.\n * @private\n */\ndiff_match_patch.prototype.patch_addContext_ = function(patch, text) {\n if (text.length == 0) {\n return;\n }\n if (patch.start2 === null) {\n throw Error('patch not initialized');\n }\n var pattern = text.substring(patch.start2, patch.start2 + patch.length1);\n var padding = 0;\n\n // Look for the first and last matches of pattern in text. If two different\n // matches are found, increase the pattern length.\n while (text.indexOf(pattern) != text.lastIndexOf(pattern) &&\n pattern.length < this.Match_MaxBits - this.Patch_Margin -\n this.Patch_Margin) {\n padding += this.Patch_Margin;\n pattern = text.substring(patch.start2 - padding,\n patch.start2 + patch.length1 + padding);\n }\n // Add one chunk for good luck.\n padding += this.Patch_Margin;\n\n // Add the prefix.\n var prefix = text.substring(patch.start2 - padding, patch.start2);\n if (prefix) {\n patch.diffs.unshift(new diff_match_patch.Diff(DIFF_EQUAL, prefix));\n }\n // Add the suffix.\n var suffix = text.substring(patch.start2 + patch.length1,\n patch.start2 + patch.length1 + padding);\n if (suffix) {\n patch.diffs.push(new diff_match_patch.Diff(DIFF_EQUAL, suffix));\n }\n\n // Roll back the start points.\n patch.start1 -= prefix.length;\n patch.start2 -= prefix.length;\n // Extend the lengths.\n patch.length1 += prefix.length + suffix.length;\n patch.length2 += prefix.length + suffix.length;\n};\n\n\n/**\n * Compute a list of patches to turn text1 into text2.\n * Use diffs if provided, otherwise compute it ourselves.\n * There are four ways to call this function, depending on what data is\n * available to the caller:\n * Method 1:\n * a = text1, b = text2\n * Method 2:\n * a = diffs\n * Method 3 (optimal):\n * a = text1, b = diffs\n * Method 4 (deprecated, use method 3):\n * a = text1, b = text2, c = diffs\n *\n * @param {string|!Array.} a text1 (methods 1,3,4) or\n * Array of diff tuples for text1 to text2 (method 2).\n * @param {string|!Array.=} opt_b text2 (methods 1,4) or\n * Array of diff tuples for text1 to text2 (method 3) or undefined (method 2).\n * @param {string|!Array.=} opt_c Array of diff tuples\n * for text1 to text2 (method 4) or undefined (methods 1,2,3).\n * @return {!Array.} Array of Patch objects.\n */\ndiff_match_patch.prototype.patch_make = function(a, opt_b, opt_c) {\n var text1, diffs;\n if (typeof a == 'string' && typeof opt_b == 'string' &&\n typeof opt_c == 'undefined') {\n // Method 1: text1, text2\n // Compute diffs from text1 and text2.\n text1 = /** @type {string} */(a);\n diffs = this.diff_main(text1, /** @type {string} */(opt_b), true);\n if (diffs.length > 2) {\n this.diff_cleanupSemantic(diffs);\n this.diff_cleanupEfficiency(diffs);\n }\n } else if (a && typeof a == 'object' && typeof opt_b == 'undefined' &&\n typeof opt_c == 'undefined') {\n // Method 2: diffs\n // Compute text1 from diffs.\n diffs = /** @type {!Array.} */(a);\n text1 = this.diff_text1(diffs);\n } else if (typeof a == 'string' && opt_b && typeof opt_b == 'object' &&\n typeof opt_c == 'undefined') {\n // Method 3: text1, diffs\n text1 = /** @type {string} */(a);\n diffs = /** @type {!Array.} */(opt_b);\n } else if (typeof a == 'string' && typeof opt_b == 'string' &&\n opt_c && typeof opt_c == 'object') {\n // Method 4: text1, text2, diffs\n // text2 is not used.\n text1 = /** @type {string} */(a);\n diffs = /** @type {!Array.} */(opt_c);\n } else {\n throw new Error('Unknown call format to patch_make.');\n }\n\n if (diffs.length === 0) {\n return []; // Get rid of the null case.\n }\n var patches = [];\n var patch = new diff_match_patch.patch_obj();\n var patchDiffLength = 0; // Keeping our own length var is faster in JS.\n var char_count1 = 0; // Number of characters into the text1 string.\n var char_count2 = 0; // Number of characters into the text2 string.\n // Start with text1 (prepatch_text) and apply the diffs until we arrive at\n // text2 (postpatch_text). We recreate the patches one by one to determine\n // context info.\n var prepatch_text = text1;\n var postpatch_text = text1;\n for (var x = 0; x < diffs.length; x++) {\n var diff_type = diffs[x][0];\n var diff_text = diffs[x][1];\n\n if (!patchDiffLength && diff_type !== DIFF_EQUAL) {\n // A new patch starts here.\n patch.start1 = char_count1;\n patch.start2 = char_count2;\n }\n\n switch (diff_type) {\n case DIFF_INSERT:\n patch.diffs[patchDiffLength++] = diffs[x];\n patch.length2 += diff_text.length;\n postpatch_text = postpatch_text.substring(0, char_count2) + diff_text +\n postpatch_text.substring(char_count2);\n break;\n case DIFF_DELETE:\n patch.length1 += diff_text.length;\n patch.diffs[patchDiffLength++] = diffs[x];\n postpatch_text = postpatch_text.substring(0, char_count2) +\n postpatch_text.substring(char_count2 +\n diff_text.length);\n break;\n case DIFF_EQUAL:\n if (diff_text.length <= 2 * this.Patch_Margin &&\n patchDiffLength && diffs.length != x + 1) {\n // Small equality inside a patch.\n patch.diffs[patchDiffLength++] = diffs[x];\n patch.length1 += diff_text.length;\n patch.length2 += diff_text.length;\n } else if (diff_text.length >= 2 * this.Patch_Margin) {\n // Time for a new patch.\n if (patchDiffLength) {\n this.patch_addContext_(patch, prepatch_text);\n patches.push(patch);\n patch = new diff_match_patch.patch_obj();\n patchDiffLength = 0;\n // Unlike Unidiff, our patch lists have a rolling context.\n // https://github.com/google/diff-match-patch/wiki/Unidiff\n // Update prepatch text & pos to reflect the application of the\n // just completed patch.\n prepatch_text = postpatch_text;\n char_count1 = char_count2;\n }\n }\n break;\n }\n\n // Update the current character count.\n if (diff_type !== DIFF_INSERT) {\n char_count1 += diff_text.length;\n }\n if (diff_type !== DIFF_DELETE) {\n char_count2 += diff_text.length;\n }\n }\n // Pick up the leftover patch if not empty.\n if (patchDiffLength) {\n this.patch_addContext_(patch, prepatch_text);\n patches.push(patch);\n }\n\n return patches;\n};\n\n\n/**\n * Given an array of patches, return another array that is identical.\n * @param {!Array.} patches Array of Patch objects.\n * @return {!Array.} Array of Patch objects.\n */\ndiff_match_patch.prototype.patch_deepCopy = function(patches) {\n // Making deep copies is hard in JavaScript.\n var patchesCopy = [];\n for (var x = 0; x < patches.length; x++) {\n var patch = patches[x];\n var patchCopy = new diff_match_patch.patch_obj();\n patchCopy.diffs = [];\n for (var y = 0; y < patch.diffs.length; y++) {\n patchCopy.diffs[y] =\n new diff_match_patch.Diff(patch.diffs[y][0], patch.diffs[y][1]);\n }\n patchCopy.start1 = patch.start1;\n patchCopy.start2 = patch.start2;\n patchCopy.length1 = patch.length1;\n patchCopy.length2 = patch.length2;\n patchesCopy[x] = patchCopy;\n }\n return patchesCopy;\n};\n\n\n/**\n * Merge a set of patches onto the text. Return a patched text, as well\n * as a list of true/false values indicating which patches were applied.\n * @param {!Array.} patches Array of Patch objects.\n * @param {string} text Old text.\n * @return {!Array.>} Two element Array, containing the\n * new text and an array of boolean values.\n */\ndiff_match_patch.prototype.patch_apply = function(patches, text) {\n if (patches.length == 0) {\n return [text, []];\n }\n\n // Deep copy the patches so that no changes are made to originals.\n patches = this.patch_deepCopy(patches);\n\n var nullPadding = this.patch_addPadding(patches);\n text = nullPadding + text + nullPadding;\n\n this.patch_splitMax(patches);\n // delta keeps track of the offset between the expected and actual location\n // of the previous patch. If there are patches expected at positions 10 and\n // 20, but the first patch was found at 12, delta is 2 and the second patch\n // has an effective expected position of 22.\n var delta = 0;\n var results = [];\n for (var x = 0; x < patches.length; x++) {\n var expected_loc = patches[x].start2 + delta;\n var text1 = this.diff_text1(patches[x].diffs);\n var start_loc;\n var end_loc = -1;\n if (text1.length > this.Match_MaxBits) {\n // patch_splitMax will only provide an oversized pattern in the case of\n // a monster delete.\n start_loc = this.match_main(text, text1.substring(0, this.Match_MaxBits),\n expected_loc);\n if (start_loc != -1) {\n end_loc = this.match_main(text,\n text1.substring(text1.length - this.Match_MaxBits),\n expected_loc + text1.length - this.Match_MaxBits);\n if (end_loc == -1 || start_loc >= end_loc) {\n // Can't find valid trailing context. Drop this patch.\n start_loc = -1;\n }\n }\n } else {\n start_loc = this.match_main(text, text1, expected_loc);\n }\n if (start_loc == -1) {\n // No match found. :(\n results[x] = false;\n // Subtract the delta for this failed patch from subsequent patches.\n delta -= patches[x].length2 - patches[x].length1;\n } else {\n // Found a match. :)\n results[x] = true;\n delta = start_loc - expected_loc;\n var text2;\n if (end_loc == -1) {\n text2 = text.substring(start_loc, start_loc + text1.length);\n } else {\n text2 = text.substring(start_loc, end_loc + this.Match_MaxBits);\n }\n if (text1 == text2) {\n // Perfect match, just shove the replacement text in.\n text = text.substring(0, start_loc) +\n this.diff_text2(patches[x].diffs) +\n text.substring(start_loc + text1.length);\n } else {\n // Imperfect match. Run a diff to get a framework of equivalent\n // indices.\n var diffs = this.diff_main(text1, text2, false);\n if (text1.length > this.Match_MaxBits &&\n this.diff_levenshtein(diffs) / text1.length >\n this.Patch_DeleteThreshold) {\n // The end points match, but the content is unacceptably bad.\n results[x] = false;\n } else {\n this.diff_cleanupSemanticLossless(diffs);\n var index1 = 0;\n var index2;\n for (var y = 0; y < patches[x].diffs.length; y++) {\n var mod = patches[x].diffs[y];\n if (mod[0] !== DIFF_EQUAL) {\n index2 = this.diff_xIndex(diffs, index1);\n }\n if (mod[0] === DIFF_INSERT) { // Insertion\n text = text.substring(0, start_loc + index2) + mod[1] +\n text.substring(start_loc + index2);\n } else if (mod[0] === DIFF_DELETE) { // Deletion\n text = text.substring(0, start_loc + index2) +\n text.substring(start_loc + this.diff_xIndex(diffs,\n index1 + mod[1].length));\n }\n if (mod[0] !== DIFF_DELETE) {\n index1 += mod[1].length;\n }\n }\n }\n }\n }\n }\n // Strip the padding off.\n text = text.substring(nullPadding.length, text.length - nullPadding.length);\n return [text, results];\n};\n\n\n/**\n * Add some padding on text start and end so that edges can match something.\n * Intended to be called only from within patch_apply.\n * @param {!Array.} patches Array of Patch objects.\n * @return {string} The padding string added to each side.\n */\ndiff_match_patch.prototype.patch_addPadding = function(patches) {\n var paddingLength = this.Patch_Margin;\n var nullPadding = '';\n for (var x = 1; x <= paddingLength; x++) {\n nullPadding += String.fromCharCode(x);\n }\n\n // Bump all the patches forward.\n for (var x = 0; x < patches.length; x++) {\n patches[x].start1 += paddingLength;\n patches[x].start2 += paddingLength;\n }\n\n // Add some padding on start of first diff.\n var patch = patches[0];\n var diffs = patch.diffs;\n if (diffs.length == 0 || diffs[0][0] != DIFF_EQUAL) {\n // Add nullPadding equality.\n diffs.unshift(new diff_match_patch.Diff(DIFF_EQUAL, nullPadding));\n patch.start1 -= paddingLength; // Should be 0.\n patch.start2 -= paddingLength; // Should be 0.\n patch.length1 += paddingLength;\n patch.length2 += paddingLength;\n } else if (paddingLength > diffs[0][1].length) {\n // Grow first equality.\n var extraLength = paddingLength - diffs[0][1].length;\n diffs[0][1] = nullPadding.substring(diffs[0][1].length) + diffs[0][1];\n patch.start1 -= extraLength;\n patch.start2 -= extraLength;\n patch.length1 += extraLength;\n patch.length2 += extraLength;\n }\n\n // Add some padding on end of last diff.\n patch = patches[patches.length - 1];\n diffs = patch.diffs;\n if (diffs.length == 0 || diffs[diffs.length - 1][0] != DIFF_EQUAL) {\n // Add nullPadding equality.\n diffs.push(new diff_match_patch.Diff(DIFF_EQUAL, nullPadding));\n patch.length1 += paddingLength;\n patch.length2 += paddingLength;\n } else if (paddingLength > diffs[diffs.length - 1][1].length) {\n // Grow last equality.\n var extraLength = paddingLength - diffs[diffs.length - 1][1].length;\n diffs[diffs.length - 1][1] += nullPadding.substring(0, extraLength);\n patch.length1 += extraLength;\n patch.length2 += extraLength;\n }\n\n return nullPadding;\n};\n\n\n/**\n * Look through the patches and break up any which are longer than the maximum\n * limit of the match algorithm.\n * Intended to be called only from within patch_apply.\n * @param {!Array.} patches Array of Patch objects.\n */\ndiff_match_patch.prototype.patch_splitMax = function(patches) {\n var patch_size = this.Match_MaxBits;\n for (var x = 0; x < patches.length; x++) {\n if (patches[x].length1 <= patch_size) {\n continue;\n }\n var bigpatch = patches[x];\n // Remove the big old patch.\n patches.splice(x--, 1);\n var start1 = bigpatch.start1;\n var start2 = bigpatch.start2;\n var precontext = '';\n while (bigpatch.diffs.length !== 0) {\n // Create one of several smaller patches.\n var patch = new diff_match_patch.patch_obj();\n var empty = true;\n patch.start1 = start1 - precontext.length;\n patch.start2 = start2 - precontext.length;\n if (precontext !== '') {\n patch.length1 = patch.length2 = precontext.length;\n patch.diffs.push(new diff_match_patch.Diff(DIFF_EQUAL, precontext));\n }\n while (bigpatch.diffs.length !== 0 &&\n patch.length1 < patch_size - this.Patch_Margin) {\n var diff_type = bigpatch.diffs[0][0];\n var diff_text = bigpatch.diffs[0][1];\n if (diff_type === DIFF_INSERT) {\n // Insertions are harmless.\n patch.length2 += diff_text.length;\n start2 += diff_text.length;\n patch.diffs.push(bigpatch.diffs.shift());\n empty = false;\n } else if (diff_type === DIFF_DELETE && patch.diffs.length == 1 &&\n patch.diffs[0][0] == DIFF_EQUAL &&\n diff_text.length > 2 * patch_size) {\n // This is a large deletion. Let it pass in one chunk.\n patch.length1 += diff_text.length;\n start1 += diff_text.length;\n empty = false;\n patch.diffs.push(new diff_match_patch.Diff(diff_type, diff_text));\n bigpatch.diffs.shift();\n } else {\n // Deletion or equality. Only take as much as we can stomach.\n diff_text = diff_text.substring(0,\n patch_size - patch.length1 - this.Patch_Margin);\n patch.length1 += diff_text.length;\n start1 += diff_text.length;\n if (diff_type === DIFF_EQUAL) {\n patch.length2 += diff_text.length;\n start2 += diff_text.length;\n } else {\n empty = false;\n }\n patch.diffs.push(new diff_match_patch.Diff(diff_type, diff_text));\n if (diff_text == bigpatch.diffs[0][1]) {\n bigpatch.diffs.shift();\n } else {\n bigpatch.diffs[0][1] =\n bigpatch.diffs[0][1].substring(diff_text.length);\n }\n }\n }\n // Compute the head context for the next patch.\n precontext = this.diff_text2(patch.diffs);\n precontext =\n precontext.substring(precontext.length - this.Patch_Margin);\n // Append the end context for this patch.\n var postcontext = this.diff_text1(bigpatch.diffs)\n .substring(0, this.Patch_Margin);\n if (postcontext !== '') {\n patch.length1 += postcontext.length;\n patch.length2 += postcontext.length;\n if (patch.diffs.length !== 0 &&\n patch.diffs[patch.diffs.length - 1][0] === DIFF_EQUAL) {\n patch.diffs[patch.diffs.length - 1][1] += postcontext;\n } else {\n patch.diffs.push(new diff_match_patch.Diff(DIFF_EQUAL, postcontext));\n }\n }\n if (!empty) {\n patches.splice(++x, 0, patch);\n }\n }\n }\n};\n\n\n/**\n * Take a list of patches and return a textual representation.\n * @param {!Array.} patches Array of Patch objects.\n * @return {string} Text representation of patches.\n */\ndiff_match_patch.prototype.patch_toText = function(patches) {\n var text = [];\n for (var x = 0; x < patches.length; x++) {\n text[x] = patches[x];\n }\n return text.join('');\n};\n\n\n/**\n * Parse a textual representation of patches and return a list of Patch objects.\n * @param {string} textline Text representation of patches.\n * @return {!Array.} Array of Patch objects.\n * @throws {!Error} If invalid input.\n */\ndiff_match_patch.prototype.patch_fromText = function(textline) {\n var patches = [];\n if (!textline) {\n return patches;\n }\n var text = textline.split('\\n');\n var textPointer = 0;\n var patchHeader = /^@@ -(\\d+),?(\\d*) \\+(\\d+),?(\\d*) @@$/;\n while (textPointer < text.length) {\n var m = text[textPointer].match(patchHeader);\n if (!m) {\n throw new Error('Invalid patch string: ' + text[textPointer]);\n }\n var patch = new diff_match_patch.patch_obj();\n patches.push(patch);\n patch.start1 = parseInt(m[1], 10);\n if (m[2] === '') {\n patch.start1--;\n patch.length1 = 1;\n } else if (m[2] == '0') {\n patch.length1 = 0;\n } else {\n patch.start1--;\n patch.length1 = parseInt(m[2], 10);\n }\n\n patch.start2 = parseInt(m[3], 10);\n if (m[4] === '') {\n patch.start2--;\n patch.length2 = 1;\n } else if (m[4] == '0') {\n patch.length2 = 0;\n } else {\n patch.start2--;\n patch.length2 = parseInt(m[4], 10);\n }\n textPointer++;\n\n while (textPointer < text.length) {\n var sign = text[textPointer].charAt(0);\n try {\n var line = decodeURI(text[textPointer].substring(1));\n } catch (ex) {\n // Malformed URI sequence.\n throw new Error('Illegal escape in patch_fromText: ' + line);\n }\n if (sign == '-') {\n // Deletion.\n patch.diffs.push(new diff_match_patch.Diff(DIFF_DELETE, line));\n } else if (sign == '+') {\n // Insertion.\n patch.diffs.push(new diff_match_patch.Diff(DIFF_INSERT, line));\n } else if (sign == ' ') {\n // Minor equality.\n patch.diffs.push(new diff_match_patch.Diff(DIFF_EQUAL, line));\n } else if (sign == '@') {\n // Start of next patch.\n break;\n } else if (sign === '') {\n // Blank line? Whatever.\n } else {\n // WTF?\n throw new Error('Invalid patch mode \"' + sign + '\" in: ' + line);\n }\n textPointer++;\n }\n }\n return patches;\n};\n\n\n/**\n * Class representing one patch operation.\n * @constructor\n */\ndiff_match_patch.patch_obj = function() {\n /** @type {!Array.} */\n this.diffs = [];\n /** @type {?number} */\n this.start1 = null;\n /** @type {?number} */\n this.start2 = null;\n /** @type {number} */\n this.length1 = 0;\n /** @type {number} */\n this.length2 = 0;\n};\n\n\n/**\n * Emulate GNU diff's format.\n * Header: @@ -382,8 +481,9 @@\n * Indices are printed as 1-based, not 0-based.\n * @return {string} The GNU diff string.\n */\ndiff_match_patch.patch_obj.prototype.toString = function() {\n var coords1, coords2;\n if (this.length1 === 0) {\n coords1 = this.start1 + ',0';\n } else if (this.length1 == 1) {\n coords1 = this.start1 + 1;\n } else {\n coords1 = (this.start1 + 1) + ',' + this.length1;\n }\n if (this.length2 === 0) {\n coords2 = this.start2 + ',0';\n } else if (this.length2 == 1) {\n coords2 = this.start2 + 1;\n } else {\n coords2 = (this.start2 + 1) + ',' + this.length2;\n }\n var text = ['@@ -' + coords1 + ' +' + coords2 + ' @@\\n'];\n var op;\n // Escape the body of the patch with %xx notation.\n for (var x = 0; x < this.diffs.length; x++) {\n switch (this.diffs[x][0]) {\n case DIFF_INSERT:\n op = '+';\n break;\n case DIFF_DELETE:\n op = '-';\n break;\n case DIFF_EQUAL:\n op = ' ';\n break;\n }\n text[x + 1] = op + encodeURI(this.diffs[x][1]) + '\\n';\n }\n return text.join('').replace(/%20/g, ' ');\n};\n\n\n// The following export code was added by @ForbesLindesay\nmodule.exports = diff_match_patch;\nmodule.exports['diff_match_patch'] = diff_match_patch;\nmodule.exports['DIFF_DELETE'] = DIFF_DELETE;\nmodule.exports['DIFF_INSERT'] = DIFF_INSERT;\nmodule.exports['DIFF_EQUAL'] = DIFF_EQUAL;","// CodeMirror, copyright (c) by Marijn Haverbeke and others\n// Distributed under an MIT license: https://codemirror.net/5/LICENSE\n\n(function(mod) {\n if (typeof exports == \"object\" && typeof module == \"object\") // CommonJS\n mod(require(\"../../lib/codemirror\"));\n else if (typeof define == \"function\" && define.amd) // AMD\n define([\"../../lib/codemirror\"], mod);\n else // Plain browser env\n mod(CodeMirror);\n})(function(CodeMirror) {\n \"use strict\";\n\n CodeMirror.defineSimpleMode = function(name, states) {\n CodeMirror.defineMode(name, function(config) {\n return CodeMirror.simpleMode(config, states);\n });\n };\n\n CodeMirror.simpleMode = function(config, states) {\n ensureState(states, \"start\");\n var states_ = {}, meta = states.meta || {}, hasIndentation = false;\n for (var state in states) if (state != meta && states.hasOwnProperty(state)) {\n var list = states_[state] = [], orig = states[state];\n for (var i = 0; i < orig.length; i++) {\n var data = orig[i];\n list.push(new Rule(data, states));\n if (data.indent || data.dedent) hasIndentation = true;\n }\n }\n var mode = {\n startState: function() {\n return {state: \"start\", pending: null,\n local: null, localState: null,\n indent: hasIndentation ? [] : null};\n },\n copyState: function(state) {\n var s = {state: state.state, pending: state.pending,\n local: state.local, localState: null,\n indent: state.indent && state.indent.slice(0)};\n if (state.localState)\n s.localState = CodeMirror.copyState(state.local.mode, state.localState);\n if (state.stack)\n s.stack = state.stack.slice(0);\n for (var pers = state.persistentStates; pers; pers = pers.next)\n s.persistentStates = {mode: pers.mode,\n spec: pers.spec,\n state: pers.state == state.localState ? s.localState : CodeMirror.copyState(pers.mode, pers.state),\n next: s.persistentStates};\n return s;\n },\n token: tokenFunction(states_, config),\n innerMode: function(state) { return state.local && {mode: state.local.mode, state: state.localState}; },\n indent: indentFunction(states_, meta)\n };\n if (meta) for (var prop in meta) if (meta.hasOwnProperty(prop))\n mode[prop] = meta[prop];\n return mode;\n };\n\n function ensureState(states, name) {\n if (!states.hasOwnProperty(name))\n throw new Error(\"Undefined state \" + name + \" in simple mode\");\n }\n\n function toRegex(val, caret) {\n if (!val) return /(?:)/;\n var flags = \"\";\n if (val instanceof RegExp) {\n if (val.ignoreCase) flags = \"i\";\n if (val.unicode) flags += \"u\"\n val = val.source;\n } else {\n val = String(val);\n }\n return new RegExp((caret === false ? \"\" : \"^\") + \"(?:\" + val + \")\", flags);\n }\n\n function asToken(val) {\n if (!val) return null;\n if (val.apply) return val\n if (typeof val == \"string\") return val.replace(/\\./g, \" \");\n var result = [];\n for (var i = 0; i < val.length; i++)\n result.push(val[i] && val[i].replace(/\\./g, \" \"));\n return result;\n }\n\n function Rule(data, states) {\n if (data.next || data.push) ensureState(states, data.next || data.push);\n this.regex = toRegex(data.regex);\n this.token = asToken(data.token);\n this.data = data;\n }\n\n function tokenFunction(states, config) {\n return function(stream, state) {\n if (state.pending) {\n var pend = state.pending.shift();\n if (state.pending.length == 0) state.pending = null;\n stream.pos += pend.text.length;\n return pend.token;\n }\n\n if (state.local) {\n if (state.local.end && stream.match(state.local.end)) {\n var tok = state.local.endToken || null;\n state.local = state.localState = null;\n return tok;\n } else {\n var tok = state.local.mode.token(stream, state.localState), m;\n if (state.local.endScan && (m = state.local.endScan.exec(stream.current())))\n stream.pos = stream.start + m.index;\n return tok;\n }\n }\n\n var curState = states[state.state];\n for (var i = 0; i < curState.length; i++) {\n var rule = curState[i];\n var matches = (!rule.data.sol || stream.sol()) && stream.match(rule.regex);\n if (matches) {\n if (rule.data.next) {\n state.state = rule.data.next;\n } else if (rule.data.push) {\n (state.stack || (state.stack = [])).push(state.state);\n state.state = rule.data.push;\n } else if (rule.data.pop && state.stack && state.stack.length) {\n state.state = state.stack.pop();\n }\n\n if (rule.data.mode)\n enterLocalMode(config, state, rule.data.mode, rule.token);\n if (rule.data.indent)\n state.indent.push(stream.indentation() + config.indentUnit);\n if (rule.data.dedent)\n state.indent.pop();\n var token = rule.token\n if (token && token.apply) token = token(matches)\n if (matches.length > 2 && rule.token && typeof rule.token != \"string\") {\n for (var j = 2; j < matches.length; j++)\n if (matches[j])\n (state.pending || (state.pending = [])).push({text: matches[j], token: rule.token[j - 1]});\n stream.backUp(matches[0].length - (matches[1] ? matches[1].length : 0));\n return token[0];\n } else if (token && token.join) {\n return token[0];\n } else {\n return token;\n }\n }\n }\n stream.next();\n return null;\n };\n }\n\n function cmp(a, b) {\n if (a === b) return true;\n if (!a || typeof a != \"object\" || !b || typeof b != \"object\") return false;\n var props = 0;\n for (var prop in a) if (a.hasOwnProperty(prop)) {\n if (!b.hasOwnProperty(prop) || !cmp(a[prop], b[prop])) return false;\n props++;\n }\n for (var prop in b) if (b.hasOwnProperty(prop)) props--;\n return props == 0;\n }\n\n function enterLocalMode(config, state, spec, token) {\n var pers;\n if (spec.persistent) for (var p = state.persistentStates; p && !pers; p = p.next)\n if (spec.spec ? cmp(spec.spec, p.spec) : spec.mode == p.mode) pers = p;\n var mode = pers ? pers.mode : spec.mode || CodeMirror.getMode(config, spec.spec);\n var lState = pers ? pers.state : CodeMirror.startState(mode);\n if (spec.persistent && !pers)\n state.persistentStates = {mode: mode, spec: spec.spec, state: lState, next: state.persistentStates};\n\n state.localState = lState;\n state.local = {mode: mode,\n end: spec.end && toRegex(spec.end),\n endScan: spec.end && spec.forceEnd !== false && toRegex(spec.end, false),\n endToken: token && token.join ? token[token.length - 1] : token};\n }\n\n function indexOf(val, arr) {\n for (var i = 0; i < arr.length; i++) if (arr[i] === val) return true;\n }\n\n function indentFunction(states, meta) {\n return function(state, textAfter, line) {\n if (state.local && state.local.mode.indent)\n return state.local.mode.indent(state.localState, textAfter, line);\n if (state.indent == null || state.local || meta.dontIndentStates && indexOf(state.state, meta.dontIndentStates) > -1)\n return CodeMirror.Pass;\n\n var pos = state.indent.length - 1, rules = states[state.state];\n scan: for (;;) {\n for (var i = 0; i < rules.length; i++) {\n var rule = rules[i];\n if (rule.data.dedent && rule.data.dedentIfLineStart !== false) {\n var m = rule.regex.exec(textAfter);\n if (m && m[0]) {\n pos--;\n if (rule.next || rule.push) rules = states[rule.next || rule.push];\n textAfter = textAfter.slice(m[0].length);\n continue scan;\n }\n }\n }\n break;\n }\n return pos < 0 ? 0 : state.indent[pos];\n };\n }\n});\n","import { defineComponent as M, ref as y, onMounted as j, markRaw as L, watch as x, unref as v, openBlock as b, createElementBlock as S, computed as T, nextTick as G, shallowRef as Z, getCurrentInstance as q, onBeforeUnmount as K, normalizeClass as Q, normalizeStyle as X, createBlock as Y, resolveDynamicComponent as ee, mergeProps as te } from \"vue\";\nimport \"codemirror/lib/codemirror.css\";\nimport H from \"codemirror\";\nimport \"codemirror/addon/merge/merge.css\";\nimport \"codemirror/addon/merge/merge.js\";\nimport ne from \"diff-match-patch\";\nimport \"codemirror/addon/mode/simple.js\";\n!window.CodeMirror && (window.CodeMirror = H);\nconst _ = window.CodeMirror || H, oe = M({\n name: \"DefaultMode\",\n props: {\n name: {\n type: String,\n default: `cm-textarea-${+new Date()}`\n },\n value: {\n type: String,\n default: \"\"\n },\n content: {\n type: String,\n default: \"\"\n },\n options: {\n type: Object,\n default: () => ({})\n },\n cminstance: {\n type: Object,\n default: () => null\n },\n placeholder: {\n type: String,\n default: \"\"\n }\n },\n emits: {\n ready: (e) => e,\n \"update:cminstance\": (e) => e\n },\n setup(e, { emit: o }) {\n const r = y(), t = y(null), n = () => {\n t.value = L(\n _.fromTextArea(r.value, e.options)\n ), o(\"update:cminstance\", t.value);\n const i = x(\n () => e.cminstance,\n (a) => {\n var f;\n a && ((f = e.cminstance) == null || f.setValue(e.value || e.content)), o(\"ready\", v(t)), i == null || i();\n },\n { deep: !0 }\n );\n };\n return j(() => {\n n();\n }), {\n textarea: r,\n initialize: n\n };\n }\n}), I = (e, o) => {\n const r = e.__vccOpts || e;\n for (const [t, n] of o)\n r[t] = n;\n return r;\n}, re = [\"name\", \"placeholder\"];\nfunction ae(e, o, r, t, n, i) {\n return b(), S(\"textarea\", {\n ref: \"textarea\",\n name: e.$props.name,\n placeholder: e.$props.placeholder\n }, null, 8, re);\n}\nconst V = /* @__PURE__ */ I(oe, [[\"render\", ae]]);\nwindow.diff_match_patch = ne;\nwindow.DIFF_DELETE = -1;\nwindow.DIFF_INSERT = 1;\nwindow.DIFF_EQUAL = 0;\nconst se = M({\n name: \"MergeMode\",\n props: {\n options: {\n type: Object,\n default: () => ({})\n },\n cminstance: {\n type: Object,\n default: () => ({})\n }\n },\n emits: [\"update:cminstance\", \"ready\"],\n setup(e, { emit: o }) {\n const r = y(), t = y(), n = () => {\n r.value = L(\n _.MergeView(t.value, e.options)\n ), o(\"update:cminstance\", r.value), o(\"ready\", r);\n };\n return j(() => {\n n();\n }), {\n mergeView: t,\n initialize: n\n };\n }\n}), le = { ref: \"mergeView\" };\nfunction ce(e, o, r, t, n, i) {\n return b(), S(\"div\", le, null, 512);\n}\nconst ie = /* @__PURE__ */ I(se, [[\"render\", ce]]);\nvar ue = /* @__PURE__ */ ((e) => (e.info = \"info\", e.warning = \"warning\", e.error = \"error\", e))(ue || {});\nfunction de() {\n const e = new Date(), o = e.getHours() < 10 ? `0${e.getHours()}` : e.getHours(), r = e.getMinutes() < 10 ? `0${e.getMinutes()}` : e.getMinutes(), t = e.getSeconds() < 10 ? `0${e.getSeconds()}` : e.getSeconds();\n return `${o}:${r}:${t}`;\n}\nfunction Le(e) {\n return `#link#${JSON.stringify(e)}#link#`;\n}\nfunction pe(e) {\n const o = /#link#(.+)#link#/g, r = [];\n let t;\n for (t = o.exec(e); t; ) {\n const n = document.createElement(\"a\"), i = JSON.parse(t[1]), a = Object.entries(i);\n for (const [f, u] of a)\n n.setAttribute(f, u);\n n.className = \"editor_custom_link\", n.innerHTML = \"logDownload\", r.push({\n start: t.index,\n end: t.index + t[0].length,\n node: n\n }), t = o.exec(e);\n }\n return r;\n}\nfunction Te(e = \"\", o = \"info\") {\n return `#log<${o}>log#${e}#log<${o}>log#`;\n}\nfunction ge(e) {\n const o = [];\n function r() {\n const t = /#log<(\\w*)>log#((.|\\r\\n|\\n)*?)#log<(\\w*)>log#/g;\n let n;\n for (n = t.exec(e); n; ) {\n const a = n[0].replace(/\\r\\n/g, `\n`).split(`\n`), u = n[2].replace(/\\r\\n/g, `\n`).split(`\n`), m = document.createElement(\"span\"), c = n[1];\n m.className = `c-editor--log__${c}`;\n let d = 0;\n for (let l = 0; l < a.length; l++) {\n const p = a[l], $ = u[l], w = m.cloneNode(!1);\n w.innerText = $, o.push({\n start: n.index + d,\n end: n.index + d + p.length,\n node: w\n }), d = d + p.length + 1;\n }\n n = t.exec(e);\n }\n }\n return r(), o;\n}\nfunction Ie(e, o) {\n return `[${de()}] <${o}> ${e}`;\n}\nfunction De(e, o, r) {\n const n = new Array(Math.max(o || 15, 5)).join(r || \"=\");\n return `${n}${e}${n}`;\n}\nconst C = [\n {\n regex: /(\\[.*?\\])([ \\t]*)([ \\t])(.+)/,\n token: [\"tag\", \"\", \"error.strong\", \"error.strong\"],\n sol: !0\n // next: \"error\",\n },\n {\n regex: /(\\[.*?\\])([ \\t]*)()(.+)(.?)/,\n token: [\"tag\", \"\", \"bracket\", \"bracket\", \"hr\"],\n sol: !0\n // next: \"info\",\n },\n {\n regex: /(\\[.*?\\])([ \\t]*)()(.+)(.?)/,\n token: [\"tag\", \"\", \"comment\", \"comment\", \"hr\"],\n sol: !0\n // next: \"warning\",\n }\n];\n_.defineSimpleMode(\"fclog\", {\n start: [\n ...C,\n {\n regex: /.*/,\n token: \"hr\"\n }\n ],\n error: [\n ...C,\n {\n regex: /.*/,\n token: \"error.strong\"\n }\n ],\n info: [\n ...C,\n {\n regex: /.*/,\n token: \"bracket\"\n }\n ],\n warning: [\n ...C,\n {\n regex: /.*\\[/,\n token: \"comment\"\n }\n ]\n});\n_.defineSimpleMode(\"log\", {\n start: [\n {\n regex: /^[=]+[^=]*[=]+/,\n token: \"strong\"\n },\n {\n regex: /([^\\w])([A-Z][\\w]*)/,\n token: [\"\", \"string\"]\n },\n {\n regex: /(^[A-Z][\\w]*)/,\n token: \"string\"\n }\n // {\n // regex: /([^\\d])([0-9]+)/,\n // token: [null, 'comment']\n // },\n // {\n // regex: /(^[0-9]+)/,\n // token: 'comment'\n // }\n ]\n});\nconst me = M({\n name: \"CodemirrorFclog\",\n props: {\n value: {\n type: String,\n default: \"\"\n },\n name: {\n type: String,\n default: `cm-textarea-${+new Date()}`\n },\n options: {\n type: Object,\n default: () => ({})\n },\n cminstance: {\n type: Object,\n default: () => ({})\n },\n placeholder: {\n type: String,\n default: \"\"\n }\n },\n emits: [\"update:cminstance\", \"ready\"],\n setup(e, { emit: o }) {\n const r = y(), t = y(null), n = (a = e.cminstance) => {\n a.getAllMarks().forEach((c) => c.clear());\n const u = a.getValue(), m = [].concat(pe(u)).concat(ge(u));\n for (let c = 0; c < m.length; c++) {\n const d = m[c];\n a.markText(\n a.posFromIndex(d.start),\n a.posFromIndex(d.end),\n { replacedWith: d.node }\n );\n }\n }, i = () => {\n var a;\n t.value = L(\n _.fromTextArea(r.value, e.options)\n ), o(\"update:cminstance\", v(t)), (a = t.value) == null || a.on(\"change\", n);\n };\n return x(\n () => e.cminstance,\n (a) => {\n var f;\n a && (n(e.cminstance), (f = e.cminstance) == null || f.setValue(e.value), o(\"ready\", t));\n },\n { deep: !0, immediate: !0 }\n ), j(() => {\n i();\n }), {\n initialize: i,\n textarea: r\n };\n }\n}), fe = [\"name\", \"placeholder\"];\nfunction he(e, o, r, t, n, i) {\n return b(), S(\"textarea\", {\n ref: \"textarea\",\n name: e.$props.name,\n placeholder: e.$props.placeholder\n }, null, 8, fe);\n}\nconst ve = /* @__PURE__ */ I(me, [[\"render\", he]]), R = {\n \"update:value\": () => !0,\n change: (e, o) => ({ value: e, cm: o }),\n input: () => !0,\n ready: (e) => e\n}, ye = [\n \"changes\",\n \"scroll\",\n \"beforeChange\",\n \"cursorActivity\",\n \"keyHandled\",\n \"inputRead\",\n \"electricInput\",\n \"beforeSelectionChange\",\n \"viewportChange\",\n \"swapDoc\",\n \"gutterClick\",\n \"gutterContextMenu\",\n \"focus\",\n \"blur\",\n \"refresh\",\n \"optionChange\",\n \"scrollCursorIntoView\",\n \"update\"\n], we = () => {\n const e = {};\n return ye.forEach((o) => {\n e[o] = (...r) => r;\n }), e;\n}, ke = { ...R, ...we() }, O = {\n mode: \"text\",\n // Language mode\n theme: \"default\",\n // Theme\n lineNumbers: !0,\n // Display line number\n smartIndent: !0,\n // Intelligent indentation\n indentUnit: 2\n};\nfunction $e(e) {\n Promise.resolve().then(() => {\n const o = e.getScrollInfo();\n e.scrollTo(o.left, o.height);\n });\n}\nconst xe = ({\n props: e,\n cminstance: o,\n emit: r,\n internalInstance: t,\n content: n\n}) => {\n const i = T(\n () => {\n var u;\n return e.merge ? (u = v(o)) == null ? void 0 : u.editor() : v(o);\n }\n ), a = () => {\n const u = [];\n return Object.keys(t == null ? void 0 : t.vnode.props).forEach((m) => {\n if (m.startsWith(\"on\")) {\n const c = m.replace(m[2], m[2].toLowerCase()).slice(2);\n !R[c] && u.push(c);\n }\n }), u;\n };\n return {\n listenerEvents: () => {\n i.value.on(\"change\", (c) => {\n const d = c.getValue();\n d === n.value && d !== \"\" || (n.value = d, r(\"update:value\", n.value || \"\"), r(\"input\", n.value || \" \"), Promise.resolve().then(() => {\n r(\"change\", n.value, c);\n }), e.keepCursorInEnd && $e(c));\n });\n const u = {};\n a().filter((c) => !u[c] && (u[c] = !0)).forEach((c) => {\n i.value.on(c, (...d) => {\n r(c, ...d);\n });\n });\n }\n };\n};\nfunction _e({\n props: e,\n cminstance: o,\n presetRef: r\n}) {\n const t = y(null), n = y(null), i = T(\n () => {\n var l;\n return e.merge ? (l = v(o)) == null ? void 0 : l.editor() : v(o);\n }\n ), a = () => {\n G(() => {\n var l;\n (l = i.value) == null || l.refresh();\n });\n }, f = (l = e.width, p = e.height) => {\n var w;\n t.value = String(l).replace(\"px\", \"\"), n.value = String(p).replace(\"px\", \"\");\n const $ = n.value;\n (w = i.value) == null || w.setSize(t.value, $);\n }, u = () => {\n var p;\n const l = (p = i.value) == null ? void 0 : p.getWrapperElement();\n l == null || l.remove();\n }, m = () => {\n var p, $, w;\n const l = (p = i.value) == null ? void 0 : p.getDoc().getHistory();\n ($ = r.value) == null || $.initialize(), u(), (w = i.value) == null || w.getDoc().setHistory(l);\n }, c = () => {\n const l = document.querySelector(\n \".CodeMirror-gutters\"\n );\n return (l == null ? void 0 : l.style.left.replace(\"px\", \"\")) !== \"0\";\n };\n return {\n reload: m,\n refresh: a,\n resize: f,\n destroy: u,\n containerHeight: n,\n reviseStyle: () => {\n if (a(), !c())\n return;\n const l = setInterval(() => {\n c() ? a() : clearInterval(l);\n }, 60), p = setTimeout(() => {\n clearInterval(l), clearTimeout(p);\n }, 400);\n }\n };\n}\nconst F = /* @__PURE__ */ M({\n __name: \"index\",\n props: {\n value: {\n type: String,\n default: \"\"\n },\n options: {\n type: Object,\n default: () => O\n },\n globalOptions: {\n type: Object,\n default: () => O\n },\n placeholder: {\n type: String,\n default: \"\"\n },\n border: {\n type: Boolean,\n default: !1\n },\n width: {\n type: [String, Number],\n default: null\n },\n height: {\n type: [String, Number],\n default: null\n },\n originalStyle: {\n type: Boolean,\n default: !1\n },\n keepCursorInEnd: {\n type: Boolean,\n default: !1\n },\n merge: {\n type: Boolean,\n default: !1\n },\n name: {\n type: String,\n default: \"\"\n },\n marker: {\n type: Function,\n default: () => null\n },\n unseenLines: {\n type: Array,\n default: () => []\n }\n },\n emits: ke,\n setup(e, { expose: o, emit: r }) {\n var N, A;\n const t = e;\n typeof Object.assign != \"function\" && Object.defineProperty(Object, \"assign\", {\n value(s) {\n if (s == null)\n throw new TypeError(\"Cannot convert undefined or null to object\");\n const g = Object(s);\n for (let h = 1; h < arguments.length; h++) {\n const k = arguments[h];\n if (k != null)\n for (const E in k)\n Object.prototype.hasOwnProperty.call(k, E) && (g[E] = k[E]);\n }\n return g;\n },\n writable: !0,\n configurable: !0\n });\n const n = y(null), i = y(\"\"), a = Z(V), f = y({\n ...O,\n ...t.globalOptions,\n ...t.options\n }), u = q(), m = t.name || ((A = (N = u == null ? void 0 : u.parent) == null ? void 0 : N.type) == null ? void 0 : A.name) || void 0, c = y(null), d = T(\n () => {\n var s;\n return t.merge ? (s = v(n)) == null ? void 0 : s.editor() : v(n);\n }\n ), { refresh: l, resize: p, destroy: $, containerHeight: w, reviseStyle: B } = _e({\n props: t,\n cminstance: n,\n presetRef: c\n }), { listenerEvents: P } = xe({\n props: t,\n cminstance: n,\n emit: r,\n internalInstance: u,\n content: i\n }), D = () => {\n t.unseenLines !== void 0 && t.marker !== void 0 && t.unseenLines.forEach((s) => {\n var h, k;\n const g = (h = n.value) == null ? void 0 : h.lineInfo(s);\n (k = n.value) == null || k.setGutterMarker(\n s,\n \"breakpoints\",\n g != null && g.gutterMarkers ? null : t.marker()\n );\n });\n }, U = (s) => {\n var h, k;\n const g = (h = n.value) == null ? void 0 : h.getValue();\n s !== g && ((k = n.value) == null || k.setValue(s), i.value = s, B()), D();\n }, W = () => {\n P(), D(), p(t.width, t.height), r(\"ready\", n.value), x(\n [() => t.width, () => t.height],\n ([s, g]) => {\n p(s, g);\n },\n { deep: !0 }\n );\n }, J = () => {\n if (t.options.mode === \"fclog\" || t.options.mode === \"log\") {\n a.value = ve;\n return;\n }\n if (t.merge) {\n a.value = ie;\n return;\n }\n a.value = V;\n };\n return x(\n () => t.options,\n (s) => {\n var g;\n for (const h in t.options)\n (g = d.value) == null || g.setOption(\n h,\n v(s[h])\n );\n },\n { deep: !0 }\n ), x(\n () => t.value,\n (s) => {\n U(s);\n }\n ), x(() => t.merge, J, { immediate: !0 }), K(() => {\n $();\n }), o({\n cminstance: n,\n resize: p,\n refresh: l,\n destroy: $\n }), (s, g) => (b(), S(\"div\", {\n class: Q([\"codemirror-container\", {\n merge: s.$props.merge,\n bordered: s.$props.border || s.$props.merge && !t.originalStyle,\n \"width-auto\": !s.$props.width || s.$props.width == \"100%\",\n \"height-auto\": !s.$props.height || s.$props.height == \"100%\",\n \"original-style\": t.originalStyle\n }]),\n style: X({\n height: v(w) + \"px\"\n })\n }, [\n (b(), Y(ee(v(a)), te({\n ref_key: \"presetRef\",\n ref: c,\n cminstance: n.value,\n \"onUpdate:cminstance\": g[0] || (g[0] = (h) => n.value = h),\n style: { height: \"100%\" }\n }, {\n ...s.$props,\n ...s.$attrs,\n options: f.value,\n name: v(m),\n content: i.value\n }, { onReady: W }), null, 16, [\"cminstance\"]))\n ], 6));\n }\n});\nconst z = (e, o) => (o && o.options && (F.props.globalOptions.default = () => o.options), e.component((o == null ? void 0 : o.componentName) || \"Codemirror\", F), e), Ne = window.CodeMirror || _, Ae = z, Ve = z;\nfunction styleInject(css,ref){if(ref===void 0){ref={}}var insertAt=ref.insertAt;if(!css||typeof document===\"undefined\"){return}var head=document.head||document.getElementsByTagName(\"head\")[0];var style=document.createElement(\"style\");style.type=\"text/css\";if(insertAt===\"top\"){if(head.firstChild){head.insertBefore(style,head.firstChild)}else{head.appendChild(style)}}else{head.appendChild(style)}if(style.styleSheet){style.styleSheet.cssText=css}else{style.appendChild(document.createTextNode(css))}};styleInject(`.codemirror-container {\n position: relative;\n display: inline-block;\n height: 100%;\n width: fit-content;\n font-size: 12px;\n overflow: hidden;\n}\n.codemirror-container.bordered {\n border-radius: 4px;\n border: 1px solid #dddddd;\n}\n.codemirror-container.width-auto {\n width: 100%;\n}\n.codemirror-container.height-auto {\n height: 100%;\n}\n.codemirror-container.height-auto .CodeMirror,\n.codemirror-container.height-auto .cm-s-default {\n height: 100% !important;\n}\n.codemirror-container .editor_custom_link {\n cursor: pointer;\n color: #1474f1;\n text-decoration: underline;\n}\n.codemirror-container .editor_custom_link:hover {\n color: #04b4fa;\n}\n.codemirror-container:not(.original-style) .CodeMirror-lines .CodeMirror-placeholder.CodeMirror-line-like {\n color: #666;\n}\n.codemirror-container:not(.original-style) .CodeMirror,\n.codemirror-container:not(.original-style) .CodeMirror-merge-pane {\n height: 100%;\n font-family: consolas !important;\n}\n.codemirror-container:not(.original-style) .CodeMirror-merge,\n.codemirror-container:not(.original-style) .CodeMirror-merge-right .CodeMirror {\n height: 100%;\n border: none !important;\n}\n.codemirror-container:not(.original-style) .c-editor--log__error {\n color: #bb0606;\n font-weight: bold;\n}\n.codemirror-container:not(.original-style) .c-editor--log__info {\n color: #333333;\n font-weight: bold;\n}\n.codemirror-container:not(.original-style) .c-editor--log__warning {\n color: #ee9900;\n}\n.codemirror-container:not(.original-style) .c-editor--log__success {\n color: #669600;\n}\n.codemirror-container:not(.original-style) .cm-header,\n.codemirror-container:not(.original-style) .cm-strong {\n font-weight: bold;\n}\n`);\nexport {\n Ne as CodeMirror,\n Ae as GlobalCmComponent,\n Ve as InstallCodemirro,\n F as VueCodemirror,\n Le as createLinkMark,\n Ie as createLog,\n Te as createLogMark,\n De as createTitle,\n F as default,\n pe as getLinkMarks,\n de as getLocalTime,\n ge as getLogMark,\n ue as logErrorType\n};\n","/*jshint node:true */\n/*\n The MIT License (MIT)\n\n Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.\n\n Permission is hereby granted, free of charge, to any person\n obtaining a copy of this software and associated documentation files\n (the \"Software\"), to deal in the Software without restriction,\n including without limitation the rights to use, copy, modify, merge,\n publish, distribute, sublicense, and/or sell copies of the Software,\n and to permit persons to whom the Software is furnished to do so,\n subject to the following conditions:\n\n The above copyright notice and this permission notice shall be\n included in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n*/\n\n'use strict';\n\nfunction OutputLine(parent) {\n this.__parent = parent;\n this.__character_count = 0;\n // use indent_count as a marker for this.__lines that have preserved indentation\n this.__indent_count = -1;\n this.__alignment_count = 0;\n this.__wrap_point_index = 0;\n this.__wrap_point_character_count = 0;\n this.__wrap_point_indent_count = -1;\n this.__wrap_point_alignment_count = 0;\n\n this.__items = [];\n}\n\nOutputLine.prototype.clone_empty = function() {\n var line = new OutputLine(this.__parent);\n line.set_indent(this.__indent_count, this.__alignment_count);\n return line;\n};\n\nOutputLine.prototype.item = function(index) {\n if (index < 0) {\n return this.__items[this.__items.length + index];\n } else {\n return this.__items[index];\n }\n};\n\nOutputLine.prototype.has_match = function(pattern) {\n for (var lastCheckedOutput = this.__items.length - 1; lastCheckedOutput >= 0; lastCheckedOutput--) {\n if (this.__items[lastCheckedOutput].match(pattern)) {\n return true;\n }\n }\n return false;\n};\n\nOutputLine.prototype.set_indent = function(indent, alignment) {\n if (this.is_empty()) {\n this.__indent_count = indent || 0;\n this.__alignment_count = alignment || 0;\n this.__character_count = this.__parent.get_indent_size(this.__indent_count, this.__alignment_count);\n }\n};\n\nOutputLine.prototype._set_wrap_point = function() {\n if (this.__parent.wrap_line_length) {\n this.__wrap_point_index = this.__items.length;\n this.__wrap_point_character_count = this.__character_count;\n this.__wrap_point_indent_count = this.__parent.next_line.__indent_count;\n this.__wrap_point_alignment_count = this.__parent.next_line.__alignment_count;\n }\n};\n\nOutputLine.prototype._should_wrap = function() {\n return this.__wrap_point_index &&\n this.__character_count > this.__parent.wrap_line_length &&\n this.__wrap_point_character_count > this.__parent.next_line.__character_count;\n};\n\nOutputLine.prototype._allow_wrap = function() {\n if (this._should_wrap()) {\n this.__parent.add_new_line();\n var next = this.__parent.current_line;\n next.set_indent(this.__wrap_point_indent_count, this.__wrap_point_alignment_count);\n next.__items = this.__items.slice(this.__wrap_point_index);\n this.__items = this.__items.slice(0, this.__wrap_point_index);\n\n next.__character_count += this.__character_count - this.__wrap_point_character_count;\n this.__character_count = this.__wrap_point_character_count;\n\n if (next.__items[0] === \" \") {\n next.__items.splice(0, 1);\n next.__character_count -= 1;\n }\n return true;\n }\n return false;\n};\n\nOutputLine.prototype.is_empty = function() {\n return this.__items.length === 0;\n};\n\nOutputLine.prototype.last = function() {\n if (!this.is_empty()) {\n return this.__items[this.__items.length - 1];\n } else {\n return null;\n }\n};\n\nOutputLine.prototype.push = function(item) {\n this.__items.push(item);\n var last_newline_index = item.lastIndexOf('\\n');\n if (last_newline_index !== -1) {\n this.__character_count = item.length - last_newline_index;\n } else {\n this.__character_count += item.length;\n }\n};\n\nOutputLine.prototype.pop = function() {\n var item = null;\n if (!this.is_empty()) {\n item = this.__items.pop();\n this.__character_count -= item.length;\n }\n return item;\n};\n\n\nOutputLine.prototype._remove_indent = function() {\n if (this.__indent_count > 0) {\n this.__indent_count -= 1;\n this.__character_count -= this.__parent.indent_size;\n }\n};\n\nOutputLine.prototype._remove_wrap_indent = function() {\n if (this.__wrap_point_indent_count > 0) {\n this.__wrap_point_indent_count -= 1;\n }\n};\nOutputLine.prototype.trim = function() {\n while (this.last() === ' ') {\n this.__items.pop();\n this.__character_count -= 1;\n }\n};\n\nOutputLine.prototype.toString = function() {\n var result = '';\n if (this.is_empty()) {\n if (this.__parent.indent_empty_lines) {\n result = this.__parent.get_indent_string(this.__indent_count);\n }\n } else {\n result = this.__parent.get_indent_string(this.__indent_count, this.__alignment_count);\n result += this.__items.join('');\n }\n return result;\n};\n\nfunction IndentStringCache(options, baseIndentString) {\n this.__cache = [''];\n this.__indent_size = options.indent_size;\n this.__indent_string = options.indent_char;\n if (!options.indent_with_tabs) {\n this.__indent_string = new Array(options.indent_size + 1).join(options.indent_char);\n }\n\n // Set to null to continue support for auto detection of base indent\n baseIndentString = baseIndentString || '';\n if (options.indent_level > 0) {\n baseIndentString = new Array(options.indent_level + 1).join(this.__indent_string);\n }\n\n this.__base_string = baseIndentString;\n this.__base_string_length = baseIndentString.length;\n}\n\nIndentStringCache.prototype.get_indent_size = function(indent, column) {\n var result = this.__base_string_length;\n column = column || 0;\n if (indent < 0) {\n result = 0;\n }\n result += indent * this.__indent_size;\n result += column;\n return result;\n};\n\nIndentStringCache.prototype.get_indent_string = function(indent_level, column) {\n var result = this.__base_string;\n column = column || 0;\n if (indent_level < 0) {\n indent_level = 0;\n result = '';\n }\n column += indent_level * this.__indent_size;\n this.__ensure_cache(column);\n result += this.__cache[column];\n return result;\n};\n\nIndentStringCache.prototype.__ensure_cache = function(column) {\n while (column >= this.__cache.length) {\n this.__add_column();\n }\n};\n\nIndentStringCache.prototype.__add_column = function() {\n var column = this.__cache.length;\n var indent = 0;\n var result = '';\n if (this.__indent_size && column >= this.__indent_size) {\n indent = Math.floor(column / this.__indent_size);\n column -= indent * this.__indent_size;\n result = new Array(indent + 1).join(this.__indent_string);\n }\n if (column) {\n result += new Array(column + 1).join(' ');\n }\n\n this.__cache.push(result);\n};\n\nfunction Output(options, baseIndentString) {\n this.__indent_cache = new IndentStringCache(options, baseIndentString);\n this.raw = false;\n this._end_with_newline = options.end_with_newline;\n this.indent_size = options.indent_size;\n this.wrap_line_length = options.wrap_line_length;\n this.indent_empty_lines = options.indent_empty_lines;\n this.__lines = [];\n this.previous_line = null;\n this.current_line = null;\n this.next_line = new OutputLine(this);\n this.space_before_token = false;\n this.non_breaking_space = false;\n this.previous_token_wrapped = false;\n // initialize\n this.__add_outputline();\n}\n\nOutput.prototype.__add_outputline = function() {\n this.previous_line = this.current_line;\n this.current_line = this.next_line.clone_empty();\n this.__lines.push(this.current_line);\n};\n\nOutput.prototype.get_line_number = function() {\n return this.__lines.length;\n};\n\nOutput.prototype.get_indent_string = function(indent, column) {\n return this.__indent_cache.get_indent_string(indent, column);\n};\n\nOutput.prototype.get_indent_size = function(indent, column) {\n return this.__indent_cache.get_indent_size(indent, column);\n};\n\nOutput.prototype.is_empty = function() {\n return !this.previous_line && this.current_line.is_empty();\n};\n\nOutput.prototype.add_new_line = function(force_newline) {\n // never newline at the start of file\n // otherwise, newline only if we didn't just add one or we're forced\n if (this.is_empty() ||\n (!force_newline && this.just_added_newline())) {\n return false;\n }\n\n // if raw output is enabled, don't print additional newlines,\n // but still return True as though you had\n if (!this.raw) {\n this.__add_outputline();\n }\n return true;\n};\n\nOutput.prototype.get_code = function(eol) {\n this.trim(true);\n\n // handle some edge cases where the last tokens\n // has text that ends with newline(s)\n var last_item = this.current_line.pop();\n if (last_item) {\n if (last_item[last_item.length - 1] === '\\n') {\n last_item = last_item.replace(/\\n+$/g, '');\n }\n this.current_line.push(last_item);\n }\n\n if (this._end_with_newline) {\n this.__add_outputline();\n }\n\n var sweet_code = this.__lines.join('\\n');\n\n if (eol !== '\\n') {\n sweet_code = sweet_code.replace(/[\\n]/g, eol);\n }\n return sweet_code;\n};\n\nOutput.prototype.set_wrap_point = function() {\n this.current_line._set_wrap_point();\n};\n\nOutput.prototype.set_indent = function(indent, alignment) {\n indent = indent || 0;\n alignment = alignment || 0;\n\n // Next line stores alignment values\n this.next_line.set_indent(indent, alignment);\n\n // Never indent your first output indent at the start of the file\n if (this.__lines.length > 1) {\n this.current_line.set_indent(indent, alignment);\n return true;\n }\n\n this.current_line.set_indent();\n return false;\n};\n\nOutput.prototype.add_raw_token = function(token) {\n for (var x = 0; x < token.newlines; x++) {\n this.__add_outputline();\n }\n this.current_line.set_indent(-1);\n this.current_line.push(token.whitespace_before);\n this.current_line.push(token.text);\n this.space_before_token = false;\n this.non_breaking_space = false;\n this.previous_token_wrapped = false;\n};\n\nOutput.prototype.add_token = function(printable_token) {\n this.__add_space_before_token();\n this.current_line.push(printable_token);\n this.space_before_token = false;\n this.non_breaking_space = false;\n this.previous_token_wrapped = this.current_line._allow_wrap();\n};\n\nOutput.prototype.__add_space_before_token = function() {\n if (this.space_before_token && !this.just_added_newline()) {\n if (!this.non_breaking_space) {\n this.set_wrap_point();\n }\n this.current_line.push(' ');\n }\n};\n\nOutput.prototype.remove_indent = function(index) {\n var output_length = this.__lines.length;\n while (index < output_length) {\n this.__lines[index]._remove_indent();\n index++;\n }\n this.current_line._remove_wrap_indent();\n};\n\nOutput.prototype.trim = function(eat_newlines) {\n eat_newlines = (eat_newlines === undefined) ? false : eat_newlines;\n\n this.current_line.trim();\n\n while (eat_newlines && this.__lines.length > 1 &&\n this.current_line.is_empty()) {\n this.__lines.pop();\n this.current_line = this.__lines[this.__lines.length - 1];\n this.current_line.trim();\n }\n\n this.previous_line = this.__lines.length > 1 ?\n this.__lines[this.__lines.length - 2] : null;\n};\n\nOutput.prototype.just_added_newline = function() {\n return this.current_line.is_empty();\n};\n\nOutput.prototype.just_added_blankline = function() {\n return this.is_empty() ||\n (this.current_line.is_empty() && this.previous_line.is_empty());\n};\n\nOutput.prototype.ensure_empty_line_above = function(starts_with, ends_with) {\n var index = this.__lines.length - 2;\n while (index >= 0) {\n var potentialEmptyLine = this.__lines[index];\n if (potentialEmptyLine.is_empty()) {\n break;\n } else if (potentialEmptyLine.item(0).indexOf(starts_with) !== 0 &&\n potentialEmptyLine.item(-1) !== ends_with) {\n this.__lines.splice(index + 1, 0, new OutputLine(this));\n this.previous_line = this.__lines[this.__lines.length - 2];\n break;\n }\n index--;\n }\n};\n\nmodule.exports.Output = Output;\n","/*jshint node:true */\n/*\n\n The MIT License (MIT)\n\n Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.\n\n Permission is hereby granted, free of charge, to any person\n obtaining a copy of this software and associated documentation files\n (the \"Software\"), to deal in the Software without restriction,\n including without limitation the rights to use, copy, modify, merge,\n publish, distribute, sublicense, and/or sell copies of the Software,\n and to permit persons to whom the Software is furnished to do so,\n subject to the following conditions:\n\n The above copyright notice and this permission notice shall be\n included in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n*/\n\n'use strict';\n\nfunction Token(type, text, newlines, whitespace_before) {\n this.type = type;\n this.text = text;\n\n // comments_before are\n // comments that have a new line before them\n // and may or may not have a newline after\n // this is a set of comments before\n this.comments_before = null; /* inline comment*/\n\n\n // this.comments_after = new TokenStream(); // no new line before and newline after\n this.newlines = newlines || 0;\n this.whitespace_before = whitespace_before || '';\n this.parent = null;\n this.next = null;\n this.previous = null;\n this.opened = null;\n this.closed = null;\n this.directives = null;\n}\n\n\nmodule.exports.Token = Token;\n","/* jshint node: true, curly: false */\n// Parts of this section of code is taken from acorn.\n//\n// Acorn was written by Marijn Haverbeke and released under an MIT\n// license. The Unicode regexps (for identifiers and whitespace) were\n// taken from [Esprima](http://esprima.org) by Ariya Hidayat.\n//\n// Git repositories for Acorn are available at\n//\n// http://marijnhaverbeke.nl/git/acorn\n// https://github.com/marijnh/acorn.git\n\n// ## Character categories\n\n\n'use strict';\n\n// acorn used char codes to squeeze the last bit of performance out\n// Beautifier is okay without that, so we're using regex\n// permit # (23), $ (36), and @ (64). @ is used in ES7 decorators.\n// 65 through 91 are uppercase letters.\n// permit _ (95).\n// 97 through 123 are lowercase letters.\nvar baseASCIIidentifierStartChars = \"\\\\x23\\\\x24\\\\x40\\\\x41-\\\\x5a\\\\x5f\\\\x61-\\\\x7a\";\n\n// inside an identifier @ is not allowed but 0-9 are.\nvar baseASCIIidentifierChars = \"\\\\x24\\\\x30-\\\\x39\\\\x41-\\\\x5a\\\\x5f\\\\x61-\\\\x7a\";\n\n// Big ugly regular expressions that match characters in the\n// whitespace, identifier, and identifier-start categories. These\n// are only applied when a character is found to actually have a\n// code point above 128.\nvar nonASCIIidentifierStartChars = \"\\\\xaa\\\\xb5\\\\xba\\\\xc0-\\\\xd6\\\\xd8-\\\\xf6\\\\xf8-\\\\u02c1\\\\u02c6-\\\\u02d1\\\\u02e0-\\\\u02e4\\\\u02ec\\\\u02ee\\\\u0370-\\\\u0374\\\\u0376\\\\u0377\\\\u037a-\\\\u037d\\\\u0386\\\\u0388-\\\\u038a\\\\u038c\\\\u038e-\\\\u03a1\\\\u03a3-\\\\u03f5\\\\u03f7-\\\\u0481\\\\u048a-\\\\u0527\\\\u0531-\\\\u0556\\\\u0559\\\\u0561-\\\\u0587\\\\u05d0-\\\\u05ea\\\\u05f0-\\\\u05f2\\\\u0620-\\\\u064a\\\\u066e\\\\u066f\\\\u0671-\\\\u06d3\\\\u06d5\\\\u06e5\\\\u06e6\\\\u06ee\\\\u06ef\\\\u06fa-\\\\u06fc\\\\u06ff\\\\u0710\\\\u0712-\\\\u072f\\\\u074d-\\\\u07a5\\\\u07b1\\\\u07ca-\\\\u07ea\\\\u07f4\\\\u07f5\\\\u07fa\\\\u0800-\\\\u0815\\\\u081a\\\\u0824\\\\u0828\\\\u0840-\\\\u0858\\\\u08a0\\\\u08a2-\\\\u08ac\\\\u0904-\\\\u0939\\\\u093d\\\\u0950\\\\u0958-\\\\u0961\\\\u0971-\\\\u0977\\\\u0979-\\\\u097f\\\\u0985-\\\\u098c\\\\u098f\\\\u0990\\\\u0993-\\\\u09a8\\\\u09aa-\\\\u09b0\\\\u09b2\\\\u09b6-\\\\u09b9\\\\u09bd\\\\u09ce\\\\u09dc\\\\u09dd\\\\u09df-\\\\u09e1\\\\u09f0\\\\u09f1\\\\u0a05-\\\\u0a0a\\\\u0a0f\\\\u0a10\\\\u0a13-\\\\u0a28\\\\u0a2a-\\\\u0a30\\\\u0a32\\\\u0a33\\\\u0a35\\\\u0a36\\\\u0a38\\\\u0a39\\\\u0a59-\\\\u0a5c\\\\u0a5e\\\\u0a72-\\\\u0a74\\\\u0a85-\\\\u0a8d\\\\u0a8f-\\\\u0a91\\\\u0a93-\\\\u0aa8\\\\u0aaa-\\\\u0ab0\\\\u0ab2\\\\u0ab3\\\\u0ab5-\\\\u0ab9\\\\u0abd\\\\u0ad0\\\\u0ae0\\\\u0ae1\\\\u0b05-\\\\u0b0c\\\\u0b0f\\\\u0b10\\\\u0b13-\\\\u0b28\\\\u0b2a-\\\\u0b30\\\\u0b32\\\\u0b33\\\\u0b35-\\\\u0b39\\\\u0b3d\\\\u0b5c\\\\u0b5d\\\\u0b5f-\\\\u0b61\\\\u0b71\\\\u0b83\\\\u0b85-\\\\u0b8a\\\\u0b8e-\\\\u0b90\\\\u0b92-\\\\u0b95\\\\u0b99\\\\u0b9a\\\\u0b9c\\\\u0b9e\\\\u0b9f\\\\u0ba3\\\\u0ba4\\\\u0ba8-\\\\u0baa\\\\u0bae-\\\\u0bb9\\\\u0bd0\\\\u0c05-\\\\u0c0c\\\\u0c0e-\\\\u0c10\\\\u0c12-\\\\u0c28\\\\u0c2a-\\\\u0c33\\\\u0c35-\\\\u0c39\\\\u0c3d\\\\u0c58\\\\u0c59\\\\u0c60\\\\u0c61\\\\u0c85-\\\\u0c8c\\\\u0c8e-\\\\u0c90\\\\u0c92-\\\\u0ca8\\\\u0caa-\\\\u0cb3\\\\u0cb5-\\\\u0cb9\\\\u0cbd\\\\u0cde\\\\u0ce0\\\\u0ce1\\\\u0cf1\\\\u0cf2\\\\u0d05-\\\\u0d0c\\\\u0d0e-\\\\u0d10\\\\u0d12-\\\\u0d3a\\\\u0d3d\\\\u0d4e\\\\u0d60\\\\u0d61\\\\u0d7a-\\\\u0d7f\\\\u0d85-\\\\u0d96\\\\u0d9a-\\\\u0db1\\\\u0db3-\\\\u0dbb\\\\u0dbd\\\\u0dc0-\\\\u0dc6\\\\u0e01-\\\\u0e30\\\\u0e32\\\\u0e33\\\\u0e40-\\\\u0e46\\\\u0e81\\\\u0e82\\\\u0e84\\\\u0e87\\\\u0e88\\\\u0e8a\\\\u0e8d\\\\u0e94-\\\\u0e97\\\\u0e99-\\\\u0e9f\\\\u0ea1-\\\\u0ea3\\\\u0ea5\\\\u0ea7\\\\u0eaa\\\\u0eab\\\\u0ead-\\\\u0eb0\\\\u0eb2\\\\u0eb3\\\\u0ebd\\\\u0ec0-\\\\u0ec4\\\\u0ec6\\\\u0edc-\\\\u0edf\\\\u0f00\\\\u0f40-\\\\u0f47\\\\u0f49-\\\\u0f6c\\\\u0f88-\\\\u0f8c\\\\u1000-\\\\u102a\\\\u103f\\\\u1050-\\\\u1055\\\\u105a-\\\\u105d\\\\u1061\\\\u1065\\\\u1066\\\\u106e-\\\\u1070\\\\u1075-\\\\u1081\\\\u108e\\\\u10a0-\\\\u10c5\\\\u10c7\\\\u10cd\\\\u10d0-\\\\u10fa\\\\u10fc-\\\\u1248\\\\u124a-\\\\u124d\\\\u1250-\\\\u1256\\\\u1258\\\\u125a-\\\\u125d\\\\u1260-\\\\u1288\\\\u128a-\\\\u128d\\\\u1290-\\\\u12b0\\\\u12b2-\\\\u12b5\\\\u12b8-\\\\u12be\\\\u12c0\\\\u12c2-\\\\u12c5\\\\u12c8-\\\\u12d6\\\\u12d8-\\\\u1310\\\\u1312-\\\\u1315\\\\u1318-\\\\u135a\\\\u1380-\\\\u138f\\\\u13a0-\\\\u13f4\\\\u1401-\\\\u166c\\\\u166f-\\\\u167f\\\\u1681-\\\\u169a\\\\u16a0-\\\\u16ea\\\\u16ee-\\\\u16f0\\\\u1700-\\\\u170c\\\\u170e-\\\\u1711\\\\u1720-\\\\u1731\\\\u1740-\\\\u1751\\\\u1760-\\\\u176c\\\\u176e-\\\\u1770\\\\u1780-\\\\u17b3\\\\u17d7\\\\u17dc\\\\u1820-\\\\u1877\\\\u1880-\\\\u18a8\\\\u18aa\\\\u18b0-\\\\u18f5\\\\u1900-\\\\u191c\\\\u1950-\\\\u196d\\\\u1970-\\\\u1974\\\\u1980-\\\\u19ab\\\\u19c1-\\\\u19c7\\\\u1a00-\\\\u1a16\\\\u1a20-\\\\u1a54\\\\u1aa7\\\\u1b05-\\\\u1b33\\\\u1b45-\\\\u1b4b\\\\u1b83-\\\\u1ba0\\\\u1bae\\\\u1baf\\\\u1bba-\\\\u1be5\\\\u1c00-\\\\u1c23\\\\u1c4d-\\\\u1c4f\\\\u1c5a-\\\\u1c7d\\\\u1ce9-\\\\u1cec\\\\u1cee-\\\\u1cf1\\\\u1cf5\\\\u1cf6\\\\u1d00-\\\\u1dbf\\\\u1e00-\\\\u1f15\\\\u1f18-\\\\u1f1d\\\\u1f20-\\\\u1f45\\\\u1f48-\\\\u1f4d\\\\u1f50-\\\\u1f57\\\\u1f59\\\\u1f5b\\\\u1f5d\\\\u1f5f-\\\\u1f7d\\\\u1f80-\\\\u1fb4\\\\u1fb6-\\\\u1fbc\\\\u1fbe\\\\u1fc2-\\\\u1fc4\\\\u1fc6-\\\\u1fcc\\\\u1fd0-\\\\u1fd3\\\\u1fd6-\\\\u1fdb\\\\u1fe0-\\\\u1fec\\\\u1ff2-\\\\u1ff4\\\\u1ff6-\\\\u1ffc\\\\u2071\\\\u207f\\\\u2090-\\\\u209c\\\\u2102\\\\u2107\\\\u210a-\\\\u2113\\\\u2115\\\\u2119-\\\\u211d\\\\u2124\\\\u2126\\\\u2128\\\\u212a-\\\\u212d\\\\u212f-\\\\u2139\\\\u213c-\\\\u213f\\\\u2145-\\\\u2149\\\\u214e\\\\u2160-\\\\u2188\\\\u2c00-\\\\u2c2e\\\\u2c30-\\\\u2c5e\\\\u2c60-\\\\u2ce4\\\\u2ceb-\\\\u2cee\\\\u2cf2\\\\u2cf3\\\\u2d00-\\\\u2d25\\\\u2d27\\\\u2d2d\\\\u2d30-\\\\u2d67\\\\u2d6f\\\\u2d80-\\\\u2d96\\\\u2da0-\\\\u2da6\\\\u2da8-\\\\u2dae\\\\u2db0-\\\\u2db6\\\\u2db8-\\\\u2dbe\\\\u2dc0-\\\\u2dc6\\\\u2dc8-\\\\u2dce\\\\u2dd0-\\\\u2dd6\\\\u2dd8-\\\\u2dde\\\\u2e2f\\\\u3005-\\\\u3007\\\\u3021-\\\\u3029\\\\u3031-\\\\u3035\\\\u3038-\\\\u303c\\\\u3041-\\\\u3096\\\\u309d-\\\\u309f\\\\u30a1-\\\\u30fa\\\\u30fc-\\\\u30ff\\\\u3105-\\\\u312d\\\\u3131-\\\\u318e\\\\u31a0-\\\\u31ba\\\\u31f0-\\\\u31ff\\\\u3400-\\\\u4db5\\\\u4e00-\\\\u9fcc\\\\ua000-\\\\ua48c\\\\ua4d0-\\\\ua4fd\\\\ua500-\\\\ua60c\\\\ua610-\\\\ua61f\\\\ua62a\\\\ua62b\\\\ua640-\\\\ua66e\\\\ua67f-\\\\ua697\\\\ua6a0-\\\\ua6ef\\\\ua717-\\\\ua71f\\\\ua722-\\\\ua788\\\\ua78b-\\\\ua78e\\\\ua790-\\\\ua793\\\\ua7a0-\\\\ua7aa\\\\ua7f8-\\\\ua801\\\\ua803-\\\\ua805\\\\ua807-\\\\ua80a\\\\ua80c-\\\\ua822\\\\ua840-\\\\ua873\\\\ua882-\\\\ua8b3\\\\ua8f2-\\\\ua8f7\\\\ua8fb\\\\ua90a-\\\\ua925\\\\ua930-\\\\ua946\\\\ua960-\\\\ua97c\\\\ua984-\\\\ua9b2\\\\ua9cf\\\\uaa00-\\\\uaa28\\\\uaa40-\\\\uaa42\\\\uaa44-\\\\uaa4b\\\\uaa60-\\\\uaa76\\\\uaa7a\\\\uaa80-\\\\uaaaf\\\\uaab1\\\\uaab5\\\\uaab6\\\\uaab9-\\\\uaabd\\\\uaac0\\\\uaac2\\\\uaadb-\\\\uaadd\\\\uaae0-\\\\uaaea\\\\uaaf2-\\\\uaaf4\\\\uab01-\\\\uab06\\\\uab09-\\\\uab0e\\\\uab11-\\\\uab16\\\\uab20-\\\\uab26\\\\uab28-\\\\uab2e\\\\uabc0-\\\\uabe2\\\\uac00-\\\\ud7a3\\\\ud7b0-\\\\ud7c6\\\\ud7cb-\\\\ud7fb\\\\uf900-\\\\ufa6d\\\\ufa70-\\\\ufad9\\\\ufb00-\\\\ufb06\\\\ufb13-\\\\ufb17\\\\ufb1d\\\\ufb1f-\\\\ufb28\\\\ufb2a-\\\\ufb36\\\\ufb38-\\\\ufb3c\\\\ufb3e\\\\ufb40\\\\ufb41\\\\ufb43\\\\ufb44\\\\ufb46-\\\\ufbb1\\\\ufbd3-\\\\ufd3d\\\\ufd50-\\\\ufd8f\\\\ufd92-\\\\ufdc7\\\\ufdf0-\\\\ufdfb\\\\ufe70-\\\\ufe74\\\\ufe76-\\\\ufefc\\\\uff21-\\\\uff3a\\\\uff41-\\\\uff5a\\\\uff66-\\\\uffbe\\\\uffc2-\\\\uffc7\\\\uffca-\\\\uffcf\\\\uffd2-\\\\uffd7\\\\uffda-\\\\uffdc\";\nvar nonASCIIidentifierChars = \"\\\\u0300-\\\\u036f\\\\u0483-\\\\u0487\\\\u0591-\\\\u05bd\\\\u05bf\\\\u05c1\\\\u05c2\\\\u05c4\\\\u05c5\\\\u05c7\\\\u0610-\\\\u061a\\\\u0620-\\\\u0649\\\\u0672-\\\\u06d3\\\\u06e7-\\\\u06e8\\\\u06fb-\\\\u06fc\\\\u0730-\\\\u074a\\\\u0800-\\\\u0814\\\\u081b-\\\\u0823\\\\u0825-\\\\u0827\\\\u0829-\\\\u082d\\\\u0840-\\\\u0857\\\\u08e4-\\\\u08fe\\\\u0900-\\\\u0903\\\\u093a-\\\\u093c\\\\u093e-\\\\u094f\\\\u0951-\\\\u0957\\\\u0962-\\\\u0963\\\\u0966-\\\\u096f\\\\u0981-\\\\u0983\\\\u09bc\\\\u09be-\\\\u09c4\\\\u09c7\\\\u09c8\\\\u09d7\\\\u09df-\\\\u09e0\\\\u0a01-\\\\u0a03\\\\u0a3c\\\\u0a3e-\\\\u0a42\\\\u0a47\\\\u0a48\\\\u0a4b-\\\\u0a4d\\\\u0a51\\\\u0a66-\\\\u0a71\\\\u0a75\\\\u0a81-\\\\u0a83\\\\u0abc\\\\u0abe-\\\\u0ac5\\\\u0ac7-\\\\u0ac9\\\\u0acb-\\\\u0acd\\\\u0ae2-\\\\u0ae3\\\\u0ae6-\\\\u0aef\\\\u0b01-\\\\u0b03\\\\u0b3c\\\\u0b3e-\\\\u0b44\\\\u0b47\\\\u0b48\\\\u0b4b-\\\\u0b4d\\\\u0b56\\\\u0b57\\\\u0b5f-\\\\u0b60\\\\u0b66-\\\\u0b6f\\\\u0b82\\\\u0bbe-\\\\u0bc2\\\\u0bc6-\\\\u0bc8\\\\u0bca-\\\\u0bcd\\\\u0bd7\\\\u0be6-\\\\u0bef\\\\u0c01-\\\\u0c03\\\\u0c46-\\\\u0c48\\\\u0c4a-\\\\u0c4d\\\\u0c55\\\\u0c56\\\\u0c62-\\\\u0c63\\\\u0c66-\\\\u0c6f\\\\u0c82\\\\u0c83\\\\u0cbc\\\\u0cbe-\\\\u0cc4\\\\u0cc6-\\\\u0cc8\\\\u0cca-\\\\u0ccd\\\\u0cd5\\\\u0cd6\\\\u0ce2-\\\\u0ce3\\\\u0ce6-\\\\u0cef\\\\u0d02\\\\u0d03\\\\u0d46-\\\\u0d48\\\\u0d57\\\\u0d62-\\\\u0d63\\\\u0d66-\\\\u0d6f\\\\u0d82\\\\u0d83\\\\u0dca\\\\u0dcf-\\\\u0dd4\\\\u0dd6\\\\u0dd8-\\\\u0ddf\\\\u0df2\\\\u0df3\\\\u0e34-\\\\u0e3a\\\\u0e40-\\\\u0e45\\\\u0e50-\\\\u0e59\\\\u0eb4-\\\\u0eb9\\\\u0ec8-\\\\u0ecd\\\\u0ed0-\\\\u0ed9\\\\u0f18\\\\u0f19\\\\u0f20-\\\\u0f29\\\\u0f35\\\\u0f37\\\\u0f39\\\\u0f41-\\\\u0f47\\\\u0f71-\\\\u0f84\\\\u0f86-\\\\u0f87\\\\u0f8d-\\\\u0f97\\\\u0f99-\\\\u0fbc\\\\u0fc6\\\\u1000-\\\\u1029\\\\u1040-\\\\u1049\\\\u1067-\\\\u106d\\\\u1071-\\\\u1074\\\\u1082-\\\\u108d\\\\u108f-\\\\u109d\\\\u135d-\\\\u135f\\\\u170e-\\\\u1710\\\\u1720-\\\\u1730\\\\u1740-\\\\u1750\\\\u1772\\\\u1773\\\\u1780-\\\\u17b2\\\\u17dd\\\\u17e0-\\\\u17e9\\\\u180b-\\\\u180d\\\\u1810-\\\\u1819\\\\u1920-\\\\u192b\\\\u1930-\\\\u193b\\\\u1951-\\\\u196d\\\\u19b0-\\\\u19c0\\\\u19c8-\\\\u19c9\\\\u19d0-\\\\u19d9\\\\u1a00-\\\\u1a15\\\\u1a20-\\\\u1a53\\\\u1a60-\\\\u1a7c\\\\u1a7f-\\\\u1a89\\\\u1a90-\\\\u1a99\\\\u1b46-\\\\u1b4b\\\\u1b50-\\\\u1b59\\\\u1b6b-\\\\u1b73\\\\u1bb0-\\\\u1bb9\\\\u1be6-\\\\u1bf3\\\\u1c00-\\\\u1c22\\\\u1c40-\\\\u1c49\\\\u1c5b-\\\\u1c7d\\\\u1cd0-\\\\u1cd2\\\\u1d00-\\\\u1dbe\\\\u1e01-\\\\u1f15\\\\u200c\\\\u200d\\\\u203f\\\\u2040\\\\u2054\\\\u20d0-\\\\u20dc\\\\u20e1\\\\u20e5-\\\\u20f0\\\\u2d81-\\\\u2d96\\\\u2de0-\\\\u2dff\\\\u3021-\\\\u3028\\\\u3099\\\\u309a\\\\ua640-\\\\ua66d\\\\ua674-\\\\ua67d\\\\ua69f\\\\ua6f0-\\\\ua6f1\\\\ua7f8-\\\\ua800\\\\ua806\\\\ua80b\\\\ua823-\\\\ua827\\\\ua880-\\\\ua881\\\\ua8b4-\\\\ua8c4\\\\ua8d0-\\\\ua8d9\\\\ua8f3-\\\\ua8f7\\\\ua900-\\\\ua909\\\\ua926-\\\\ua92d\\\\ua930-\\\\ua945\\\\ua980-\\\\ua983\\\\ua9b3-\\\\ua9c0\\\\uaa00-\\\\uaa27\\\\uaa40-\\\\uaa41\\\\uaa4c-\\\\uaa4d\\\\uaa50-\\\\uaa59\\\\uaa7b\\\\uaae0-\\\\uaae9\\\\uaaf2-\\\\uaaf3\\\\uabc0-\\\\uabe1\\\\uabec\\\\uabed\\\\uabf0-\\\\uabf9\\\\ufb20-\\\\ufb28\\\\ufe00-\\\\ufe0f\\\\ufe20-\\\\ufe26\\\\ufe33\\\\ufe34\\\\ufe4d-\\\\ufe4f\\\\uff10-\\\\uff19\\\\uff3f\";\n//var nonASCIIidentifierStart = new RegExp(\"[\" + nonASCIIidentifierStartChars + \"]\");\n//var nonASCIIidentifier = new RegExp(\"[\" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + \"]\");\n\nvar identifierStart = \"(?:\\\\\\\\u[0-9a-fA-F]{4}|[\" + baseASCIIidentifierStartChars + nonASCIIidentifierStartChars + \"])\";\nvar identifierChars = \"(?:\\\\\\\\u[0-9a-fA-F]{4}|[\" + baseASCIIidentifierChars + nonASCIIidentifierStartChars + nonASCIIidentifierChars + \"])*\";\n\nexports.identifier = new RegExp(identifierStart + identifierChars, 'g');\nexports.identifierStart = new RegExp(identifierStart);\nexports.identifierMatch = new RegExp(\"(?:\\\\\\\\u[0-9a-fA-F]{4}|[\" + baseASCIIidentifierChars + nonASCIIidentifierStartChars + nonASCIIidentifierChars + \"])+\");\n\nvar nonASCIIwhitespace = /[\\u1680\\u180e\\u2000-\\u200a\\u202f\\u205f\\u3000\\ufeff]/; // jshint ignore:line\n\n// Whether a single character denotes a newline.\n\nexports.newline = /[\\n\\r\\u2028\\u2029]/;\n\n// Matches a whole line break (where CRLF is considered a single\n// line break). Used to count lines.\n\n// in javascript, these two differ\n// in python they are the same, different methods are called on them\nexports.lineBreak = new RegExp('\\r\\n|' + exports.newline.source);\nexports.allLineBreaks = new RegExp(exports.lineBreak.source, 'g');\n","/*jshint node:true */\n/*\n\n The MIT License (MIT)\n\n Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.\n\n Permission is hereby granted, free of charge, to any person\n obtaining a copy of this software and associated documentation files\n (the \"Software\"), to deal in the Software without restriction,\n including without limitation the rights to use, copy, modify, merge,\n publish, distribute, sublicense, and/or sell copies of the Software,\n and to permit persons to whom the Software is furnished to do so,\n subject to the following conditions:\n\n The above copyright notice and this permission notice shall be\n included in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n*/\n\n'use strict';\n\nfunction Options(options, merge_child_field) {\n this.raw_options = _mergeOpts(options, merge_child_field);\n\n // Support passing the source text back with no change\n this.disabled = this._get_boolean('disabled');\n\n this.eol = this._get_characters('eol', 'auto');\n this.end_with_newline = this._get_boolean('end_with_newline');\n this.indent_size = this._get_number('indent_size', 4);\n this.indent_char = this._get_characters('indent_char', ' ');\n this.indent_level = this._get_number('indent_level');\n\n this.preserve_newlines = this._get_boolean('preserve_newlines', true);\n this.max_preserve_newlines = this._get_number('max_preserve_newlines', 32786);\n if (!this.preserve_newlines) {\n this.max_preserve_newlines = 0;\n }\n\n this.indent_with_tabs = this._get_boolean('indent_with_tabs', this.indent_char === '\\t');\n if (this.indent_with_tabs) {\n this.indent_char = '\\t';\n\n // indent_size behavior changed after 1.8.6\n // It used to be that indent_size would be\n // set to 1 for indent_with_tabs. That is no longer needed and\n // actually doesn't make sense - why not use spaces? Further,\n // that might produce unexpected behavior - tabs being used\n // for single-column alignment. So, when indent_with_tabs is true\n // and indent_size is 1, reset indent_size to 4.\n if (this.indent_size === 1) {\n this.indent_size = 4;\n }\n }\n\n // Backwards compat with 1.3.x\n this.wrap_line_length = this._get_number('wrap_line_length', this._get_number('max_char'));\n\n this.indent_empty_lines = this._get_boolean('indent_empty_lines');\n\n // valid templating languages ['django', 'erb', 'handlebars', 'php', 'smarty']\n // For now, 'auto' = all off for javascript, all on for html (and inline javascript).\n // other values ignored\n this.templating = this._get_selection_list('templating', ['auto', 'none', 'django', 'erb', 'handlebars', 'php', 'smarty'], ['auto']);\n}\n\nOptions.prototype._get_array = function(name, default_value) {\n var option_value = this.raw_options[name];\n var result = default_value || [];\n if (typeof option_value === 'object') {\n if (option_value !== null && typeof option_value.concat === 'function') {\n result = option_value.concat();\n }\n } else if (typeof option_value === 'string') {\n result = option_value.split(/[^a-zA-Z0-9_\\/\\-]+/);\n }\n return result;\n};\n\nOptions.prototype._get_boolean = function(name, default_value) {\n var option_value = this.raw_options[name];\n var result = option_value === undefined ? !!default_value : !!option_value;\n return result;\n};\n\nOptions.prototype._get_characters = function(name, default_value) {\n var option_value = this.raw_options[name];\n var result = default_value || '';\n if (typeof option_value === 'string') {\n result = option_value.replace(/\\\\r/, '\\r').replace(/\\\\n/, '\\n').replace(/\\\\t/, '\\t');\n }\n return result;\n};\n\nOptions.prototype._get_number = function(name, default_value) {\n var option_value = this.raw_options[name];\n default_value = parseInt(default_value, 10);\n if (isNaN(default_value)) {\n default_value = 0;\n }\n var result = parseInt(option_value, 10);\n if (isNaN(result)) {\n result = default_value;\n }\n return result;\n};\n\nOptions.prototype._get_selection = function(name, selection_list, default_value) {\n var result = this._get_selection_list(name, selection_list, default_value);\n if (result.length !== 1) {\n throw new Error(\n \"Invalid Option Value: The option '\" + name + \"' can only be one of the following values:\\n\" +\n selection_list + \"\\nYou passed in: '\" + this.raw_options[name] + \"'\");\n }\n\n return result[0];\n};\n\n\nOptions.prototype._get_selection_list = function(name, selection_list, default_value) {\n if (!selection_list || selection_list.length === 0) {\n throw new Error(\"Selection list cannot be empty.\");\n }\n\n default_value = default_value || [selection_list[0]];\n if (!this._is_valid_selection(default_value, selection_list)) {\n throw new Error(\"Invalid Default Value!\");\n }\n\n var result = this._get_array(name, default_value);\n if (!this._is_valid_selection(result, selection_list)) {\n throw new Error(\n \"Invalid Option Value: The option '\" + name + \"' can contain only the following values:\\n\" +\n selection_list + \"\\nYou passed in: '\" + this.raw_options[name] + \"'\");\n }\n\n return result;\n};\n\nOptions.prototype._is_valid_selection = function(result, selection_list) {\n return result.length && selection_list.length &&\n !result.some(function(item) { return selection_list.indexOf(item) === -1; });\n};\n\n\n// merges child options up with the parent options object\n// Example: obj = {a: 1, b: {a: 2}}\n// mergeOpts(obj, 'b')\n//\n// Returns: {a: 2}\nfunction _mergeOpts(allOptions, childFieldName) {\n var finalOpts = {};\n allOptions = _normalizeOpts(allOptions);\n var name;\n\n for (name in allOptions) {\n if (name !== childFieldName) {\n finalOpts[name] = allOptions[name];\n }\n }\n\n //merge in the per type settings for the childFieldName\n if (childFieldName && allOptions[childFieldName]) {\n for (name in allOptions[childFieldName]) {\n finalOpts[name] = allOptions[childFieldName][name];\n }\n }\n return finalOpts;\n}\n\nfunction _normalizeOpts(options) {\n var convertedOpts = {};\n var key;\n\n for (key in options) {\n var newKey = key.replace(/-/g, \"_\");\n convertedOpts[newKey] = options[key];\n }\n return convertedOpts;\n}\n\nmodule.exports.Options = Options;\nmodule.exports.normalizeOpts = _normalizeOpts;\nmodule.exports.mergeOpts = _mergeOpts;\n","/*jshint node:true */\n/*\n\n The MIT License (MIT)\n\n Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.\n\n Permission is hereby granted, free of charge, to any person\n obtaining a copy of this software and associated documentation files\n (the \"Software\"), to deal in the Software without restriction,\n including without limitation the rights to use, copy, modify, merge,\n publish, distribute, sublicense, and/or sell copies of the Software,\n and to permit persons to whom the Software is furnished to do so,\n subject to the following conditions:\n\n The above copyright notice and this permission notice shall be\n included in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n*/\n\n'use strict';\n\nvar BaseOptions = require('../core/options').Options;\n\nvar validPositionValues = ['before-newline', 'after-newline', 'preserve-newline'];\n\nfunction Options(options) {\n BaseOptions.call(this, options, 'js');\n\n // compatibility, re\n var raw_brace_style = this.raw_options.brace_style || null;\n if (raw_brace_style === \"expand-strict\") { //graceful handling of deprecated option\n this.raw_options.brace_style = \"expand\";\n } else if (raw_brace_style === \"collapse-preserve-inline\") { //graceful handling of deprecated option\n this.raw_options.brace_style = \"collapse,preserve-inline\";\n } else if (this.raw_options.braces_on_own_line !== undefined) { //graceful handling of deprecated option\n this.raw_options.brace_style = this.raw_options.braces_on_own_line ? \"expand\" : \"collapse\";\n // } else if (!raw_brace_style) { //Nothing exists to set it\n // raw_brace_style = \"collapse\";\n }\n\n //preserve-inline in delimited string will trigger brace_preserve_inline, everything\n //else is considered a brace_style and the last one only will have an effect\n\n var brace_style_split = this._get_selection_list('brace_style', ['collapse', 'expand', 'end-expand', 'none', 'preserve-inline']);\n\n this.brace_preserve_inline = false; //Defaults in case one or other was not specified in meta-option\n this.brace_style = \"collapse\";\n\n for (var bs = 0; bs < brace_style_split.length; bs++) {\n if (brace_style_split[bs] === \"preserve-inline\") {\n this.brace_preserve_inline = true;\n } else {\n this.brace_style = brace_style_split[bs];\n }\n }\n\n this.unindent_chained_methods = this._get_boolean('unindent_chained_methods');\n this.break_chained_methods = this._get_boolean('break_chained_methods');\n this.space_in_paren = this._get_boolean('space_in_paren');\n this.space_in_empty_paren = this._get_boolean('space_in_empty_paren');\n this.jslint_happy = this._get_boolean('jslint_happy');\n this.space_after_anon_function = this._get_boolean('space_after_anon_function');\n this.space_after_named_function = this._get_boolean('space_after_named_function');\n this.keep_array_indentation = this._get_boolean('keep_array_indentation');\n this.space_before_conditional = this._get_boolean('space_before_conditional', true);\n this.unescape_strings = this._get_boolean('unescape_strings');\n this.e4x = this._get_boolean('e4x');\n this.comma_first = this._get_boolean('comma_first');\n this.operator_position = this._get_selection('operator_position', validPositionValues);\n\n // For testing of beautify preserve:start directive\n this.test_output_raw = this._get_boolean('test_output_raw');\n\n // force this._options.space_after_anon_function to true if this._options.jslint_happy\n if (this.jslint_happy) {\n this.space_after_anon_function = true;\n }\n\n}\nOptions.prototype = new BaseOptions();\n\n\n\nmodule.exports.Options = Options;\n","/*jshint node:true */\n/*\n\n The MIT License (MIT)\n\n Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.\n\n Permission is hereby granted, free of charge, to any person\n obtaining a copy of this software and associated documentation files\n (the \"Software\"), to deal in the Software without restriction,\n including without limitation the rights to use, copy, modify, merge,\n publish, distribute, sublicense, and/or sell copies of the Software,\n and to permit persons to whom the Software is furnished to do so,\n subject to the following conditions:\n\n The above copyright notice and this permission notice shall be\n included in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n*/\n\n'use strict';\n\nvar regexp_has_sticky = RegExp.prototype.hasOwnProperty('sticky');\n\nfunction InputScanner(input_string) {\n this.__input = input_string || '';\n this.__input_length = this.__input.length;\n this.__position = 0;\n}\n\nInputScanner.prototype.restart = function() {\n this.__position = 0;\n};\n\nInputScanner.prototype.back = function() {\n if (this.__position > 0) {\n this.__position -= 1;\n }\n};\n\nInputScanner.prototype.hasNext = function() {\n return this.__position < this.__input_length;\n};\n\nInputScanner.prototype.next = function() {\n var val = null;\n if (this.hasNext()) {\n val = this.__input.charAt(this.__position);\n this.__position += 1;\n }\n return val;\n};\n\nInputScanner.prototype.peek = function(index) {\n var val = null;\n index = index || 0;\n index += this.__position;\n if (index >= 0 && index < this.__input_length) {\n val = this.__input.charAt(index);\n }\n return val;\n};\n\n// This is a JavaScript only helper function (not in python)\n// Javascript doesn't have a match method\n// and not all implementation support \"sticky\" flag.\n// If they do not support sticky then both this.match() and this.test() method\n// must get the match and check the index of the match.\n// If sticky is supported and set, this method will use it.\n// Otherwise it will check that global is set, and fall back to the slower method.\nInputScanner.prototype.__match = function(pattern, index) {\n pattern.lastIndex = index;\n var pattern_match = pattern.exec(this.__input);\n\n if (pattern_match && !(regexp_has_sticky && pattern.sticky)) {\n if (pattern_match.index !== index) {\n pattern_match = null;\n }\n }\n\n return pattern_match;\n};\n\nInputScanner.prototype.test = function(pattern, index) {\n index = index || 0;\n index += this.__position;\n\n if (index >= 0 && index < this.__input_length) {\n return !!this.__match(pattern, index);\n } else {\n return false;\n }\n};\n\nInputScanner.prototype.testChar = function(pattern, index) {\n // test one character regex match\n var val = this.peek(index);\n pattern.lastIndex = 0;\n return val !== null && pattern.test(val);\n};\n\nInputScanner.prototype.match = function(pattern) {\n var pattern_match = this.__match(pattern, this.__position);\n if (pattern_match) {\n this.__position += pattern_match[0].length;\n } else {\n pattern_match = null;\n }\n return pattern_match;\n};\n\nInputScanner.prototype.read = function(starting_pattern, until_pattern, until_after) {\n var val = '';\n var match;\n if (starting_pattern) {\n match = this.match(starting_pattern);\n if (match) {\n val += match[0];\n }\n }\n if (until_pattern && (match || !starting_pattern)) {\n val += this.readUntil(until_pattern, until_after);\n }\n return val;\n};\n\nInputScanner.prototype.readUntil = function(pattern, until_after) {\n var val = '';\n var match_index = this.__position;\n pattern.lastIndex = this.__position;\n var pattern_match = pattern.exec(this.__input);\n if (pattern_match) {\n match_index = pattern_match.index;\n if (until_after) {\n match_index += pattern_match[0].length;\n }\n } else {\n match_index = this.__input_length;\n }\n\n val = this.__input.substring(this.__position, match_index);\n this.__position = match_index;\n return val;\n};\n\nInputScanner.prototype.readUntilAfter = function(pattern) {\n return this.readUntil(pattern, true);\n};\n\nInputScanner.prototype.get_regexp = function(pattern, match_from) {\n var result = null;\n var flags = 'g';\n if (match_from && regexp_has_sticky) {\n flags = 'y';\n }\n // strings are converted to regexp\n if (typeof pattern === \"string\" && pattern !== '') {\n // result = new RegExp(pattern.replace(/[-\\/\\\\^$*+?.()|[\\]{}]/g, '\\\\$&'), flags);\n result = new RegExp(pattern, flags);\n } else if (pattern) {\n result = new RegExp(pattern.source, flags);\n }\n return result;\n};\n\nInputScanner.prototype.get_literal_regexp = function(literal_string) {\n return RegExp(literal_string.replace(/[-\\/\\\\^$*+?.()|[\\]{}]/g, '\\\\$&'));\n};\n\n/* css beautifier legacy helpers */\nInputScanner.prototype.peekUntilAfter = function(pattern) {\n var start = this.__position;\n var val = this.readUntilAfter(pattern);\n this.__position = start;\n return val;\n};\n\nInputScanner.prototype.lookBack = function(testVal) {\n var start = this.__position - 1;\n return start >= testVal.length && this.__input.substring(start - testVal.length, start)\n .toLowerCase() === testVal;\n};\n\nmodule.exports.InputScanner = InputScanner;\n","/*jshint node:true */\n/*\n\n The MIT License (MIT)\n\n Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.\n\n Permission is hereby granted, free of charge, to any person\n obtaining a copy of this software and associated documentation files\n (the \"Software\"), to deal in the Software without restriction,\n including without limitation the rights to use, copy, modify, merge,\n publish, distribute, sublicense, and/or sell copies of the Software,\n and to permit persons to whom the Software is furnished to do so,\n subject to the following conditions:\n\n The above copyright notice and this permission notice shall be\n included in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n*/\n\n'use strict';\n\nfunction TokenStream(parent_token) {\n // private\n this.__tokens = [];\n this.__tokens_length = this.__tokens.length;\n this.__position = 0;\n this.__parent_token = parent_token;\n}\n\nTokenStream.prototype.restart = function() {\n this.__position = 0;\n};\n\nTokenStream.prototype.isEmpty = function() {\n return this.__tokens_length === 0;\n};\n\nTokenStream.prototype.hasNext = function() {\n return this.__position < this.__tokens_length;\n};\n\nTokenStream.prototype.next = function() {\n var val = null;\n if (this.hasNext()) {\n val = this.__tokens[this.__position];\n this.__position += 1;\n }\n return val;\n};\n\nTokenStream.prototype.peek = function(index) {\n var val = null;\n index = index || 0;\n index += this.__position;\n if (index >= 0 && index < this.__tokens_length) {\n val = this.__tokens[index];\n }\n return val;\n};\n\nTokenStream.prototype.add = function(token) {\n if (this.__parent_token) {\n token.parent = this.__parent_token;\n }\n this.__tokens.push(token);\n this.__tokens_length += 1;\n};\n\nmodule.exports.TokenStream = TokenStream;\n","/*jshint node:true */\n/*\n\n The MIT License (MIT)\n\n Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.\n\n Permission is hereby granted, free of charge, to any person\n obtaining a copy of this software and associated documentation files\n (the \"Software\"), to deal in the Software without restriction,\n including without limitation the rights to use, copy, modify, merge,\n publish, distribute, sublicense, and/or sell copies of the Software,\n and to permit persons to whom the Software is furnished to do so,\n subject to the following conditions:\n\n The above copyright notice and this permission notice shall be\n included in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n*/\n\n'use strict';\n\nfunction Pattern(input_scanner, parent) {\n this._input = input_scanner;\n this._starting_pattern = null;\n this._match_pattern = null;\n this._until_pattern = null;\n this._until_after = false;\n\n if (parent) {\n this._starting_pattern = this._input.get_regexp(parent._starting_pattern, true);\n this._match_pattern = this._input.get_regexp(parent._match_pattern, true);\n this._until_pattern = this._input.get_regexp(parent._until_pattern);\n this._until_after = parent._until_after;\n }\n}\n\nPattern.prototype.read = function() {\n var result = this._input.read(this._starting_pattern);\n if (!this._starting_pattern || result) {\n result += this._input.read(this._match_pattern, this._until_pattern, this._until_after);\n }\n return result;\n};\n\nPattern.prototype.read_match = function() {\n return this._input.match(this._match_pattern);\n};\n\nPattern.prototype.until_after = function(pattern) {\n var result = this._create();\n result._until_after = true;\n result._until_pattern = this._input.get_regexp(pattern);\n result._update();\n return result;\n};\n\nPattern.prototype.until = function(pattern) {\n var result = this._create();\n result._until_after = false;\n result._until_pattern = this._input.get_regexp(pattern);\n result._update();\n return result;\n};\n\nPattern.prototype.starting_with = function(pattern) {\n var result = this._create();\n result._starting_pattern = this._input.get_regexp(pattern, true);\n result._update();\n return result;\n};\n\nPattern.prototype.matching = function(pattern) {\n var result = this._create();\n result._match_pattern = this._input.get_regexp(pattern, true);\n result._update();\n return result;\n};\n\nPattern.prototype._create = function() {\n return new Pattern(this._input, this);\n};\n\nPattern.prototype._update = function() {};\n\nmodule.exports.Pattern = Pattern;\n","/*jshint node:true */\n/*\n\n The MIT License (MIT)\n\n Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.\n\n Permission is hereby granted, free of charge, to any person\n obtaining a copy of this software and associated documentation files\n (the \"Software\"), to deal in the Software without restriction,\n including without limitation the rights to use, copy, modify, merge,\n publish, distribute, sublicense, and/or sell copies of the Software,\n and to permit persons to whom the Software is furnished to do so,\n subject to the following conditions:\n\n The above copyright notice and this permission notice shall be\n included in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n*/\n\n'use strict';\n\nvar Pattern = require('../core/pattern').Pattern;\n\nfunction WhitespacePattern(input_scanner, parent) {\n Pattern.call(this, input_scanner, parent);\n if (parent) {\n this._line_regexp = this._input.get_regexp(parent._line_regexp);\n } else {\n this.__set_whitespace_patterns('', '');\n }\n\n this.newline_count = 0;\n this.whitespace_before_token = '';\n}\nWhitespacePattern.prototype = new Pattern();\n\nWhitespacePattern.prototype.__set_whitespace_patterns = function(whitespace_chars, newline_chars) {\n whitespace_chars += '\\\\t ';\n newline_chars += '\\\\n\\\\r';\n\n this._match_pattern = this._input.get_regexp(\n '[' + whitespace_chars + newline_chars + ']+', true);\n this._newline_regexp = this._input.get_regexp(\n '\\\\r\\\\n|[' + newline_chars + ']');\n};\n\nWhitespacePattern.prototype.read = function() {\n this.newline_count = 0;\n this.whitespace_before_token = '';\n\n var resulting_string = this._input.read(this._match_pattern);\n if (resulting_string === ' ') {\n this.whitespace_before_token = ' ';\n } else if (resulting_string) {\n var matches = this.__split(this._newline_regexp, resulting_string);\n this.newline_count = matches.length - 1;\n this.whitespace_before_token = matches[this.newline_count];\n }\n\n return resulting_string;\n};\n\nWhitespacePattern.prototype.matching = function(whitespace_chars, newline_chars) {\n var result = this._create();\n result.__set_whitespace_patterns(whitespace_chars, newline_chars);\n result._update();\n return result;\n};\n\nWhitespacePattern.prototype._create = function() {\n return new WhitespacePattern(this._input, this);\n};\n\nWhitespacePattern.prototype.__split = function(regexp, input_string) {\n regexp.lastIndex = 0;\n var start_index = 0;\n var result = [];\n var next_match = regexp.exec(input_string);\n while (next_match) {\n result.push(input_string.substring(start_index, next_match.index));\n start_index = next_match.index + next_match[0].length;\n next_match = regexp.exec(input_string);\n }\n\n if (start_index < input_string.length) {\n result.push(input_string.substring(start_index, input_string.length));\n } else {\n result.push('');\n }\n\n return result;\n};\n\n\n\nmodule.exports.WhitespacePattern = WhitespacePattern;\n","/*jshint node:true */\n/*\n\n The MIT License (MIT)\n\n Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.\n\n Permission is hereby granted, free of charge, to any person\n obtaining a copy of this software and associated documentation files\n (the \"Software\"), to deal in the Software without restriction,\n including without limitation the rights to use, copy, modify, merge,\n publish, distribute, sublicense, and/or sell copies of the Software,\n and to permit persons to whom the Software is furnished to do so,\n subject to the following conditions:\n\n The above copyright notice and this permission notice shall be\n included in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n*/\n\n'use strict';\n\nvar InputScanner = require('../core/inputscanner').InputScanner;\nvar Token = require('../core/token').Token;\nvar TokenStream = require('../core/tokenstream').TokenStream;\nvar WhitespacePattern = require('./whitespacepattern').WhitespacePattern;\n\nvar TOKEN = {\n START: 'TK_START',\n RAW: 'TK_RAW',\n EOF: 'TK_EOF'\n};\n\nvar Tokenizer = function(input_string, options) {\n this._input = new InputScanner(input_string);\n this._options = options || {};\n this.__tokens = null;\n\n this._patterns = {};\n this._patterns.whitespace = new WhitespacePattern(this._input);\n};\n\nTokenizer.prototype.tokenize = function() {\n this._input.restart();\n this.__tokens = new TokenStream();\n\n this._reset();\n\n var current;\n var previous = new Token(TOKEN.START, '');\n var open_token = null;\n var open_stack = [];\n var comments = new TokenStream();\n\n while (previous.type !== TOKEN.EOF) {\n current = this._get_next_token(previous, open_token);\n while (this._is_comment(current)) {\n comments.add(current);\n current = this._get_next_token(previous, open_token);\n }\n\n if (!comments.isEmpty()) {\n current.comments_before = comments;\n comments = new TokenStream();\n }\n\n current.parent = open_token;\n\n if (this._is_opening(current)) {\n open_stack.push(open_token);\n open_token = current;\n } else if (open_token && this._is_closing(current, open_token)) {\n current.opened = open_token;\n open_token.closed = current;\n open_token = open_stack.pop();\n current.parent = open_token;\n }\n\n current.previous = previous;\n previous.next = current;\n\n this.__tokens.add(current);\n previous = current;\n }\n\n return this.__tokens;\n};\n\n\nTokenizer.prototype._is_first_token = function() {\n return this.__tokens.isEmpty();\n};\n\nTokenizer.prototype._reset = function() {};\n\nTokenizer.prototype._get_next_token = function(previous_token, open_token) { // jshint unused:false\n this._readWhitespace();\n var resulting_string = this._input.read(/.+/g);\n if (resulting_string) {\n return this._create_token(TOKEN.RAW, resulting_string);\n } else {\n return this._create_token(TOKEN.EOF, '');\n }\n};\n\nTokenizer.prototype._is_comment = function(current_token) { // jshint unused:false\n return false;\n};\n\nTokenizer.prototype._is_opening = function(current_token) { // jshint unused:false\n return false;\n};\n\nTokenizer.prototype._is_closing = function(current_token, open_token) { // jshint unused:false\n return false;\n};\n\nTokenizer.prototype._create_token = function(type, text) {\n var token = new Token(type, text,\n this._patterns.whitespace.newline_count,\n this._patterns.whitespace.whitespace_before_token);\n return token;\n};\n\nTokenizer.prototype._readWhitespace = function() {\n return this._patterns.whitespace.read();\n};\n\n\n\nmodule.exports.Tokenizer = Tokenizer;\nmodule.exports.TOKEN = TOKEN;\n","/*jshint node:true */\n/*\n\n The MIT License (MIT)\n\n Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.\n\n Permission is hereby granted, free of charge, to any person\n obtaining a copy of this software and associated documentation files\n (the \"Software\"), to deal in the Software without restriction,\n including without limitation the rights to use, copy, modify, merge,\n publish, distribute, sublicense, and/or sell copies of the Software,\n and to permit persons to whom the Software is furnished to do so,\n subject to the following conditions:\n\n The above copyright notice and this permission notice shall be\n included in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n*/\n\n'use strict';\n\nfunction Directives(start_block_pattern, end_block_pattern) {\n start_block_pattern = typeof start_block_pattern === 'string' ? start_block_pattern : start_block_pattern.source;\n end_block_pattern = typeof end_block_pattern === 'string' ? end_block_pattern : end_block_pattern.source;\n this.__directives_block_pattern = new RegExp(start_block_pattern + / beautify( \\w+[:]\\w+)+ /.source + end_block_pattern, 'g');\n this.__directive_pattern = / (\\w+)[:](\\w+)/g;\n\n this.__directives_end_ignore_pattern = new RegExp(start_block_pattern + /\\sbeautify\\signore:end\\s/.source + end_block_pattern, 'g');\n}\n\nDirectives.prototype.get_directives = function(text) {\n if (!text.match(this.__directives_block_pattern)) {\n return null;\n }\n\n var directives = {};\n this.__directive_pattern.lastIndex = 0;\n var directive_match = this.__directive_pattern.exec(text);\n\n while (directive_match) {\n directives[directive_match[1]] = directive_match[2];\n directive_match = this.__directive_pattern.exec(text);\n }\n\n return directives;\n};\n\nDirectives.prototype.readIgnored = function(input) {\n return input.readUntilAfter(this.__directives_end_ignore_pattern);\n};\n\n\nmodule.exports.Directives = Directives;\n","/*jshint node:true */\n/*\n\n The MIT License (MIT)\n\n Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.\n\n Permission is hereby granted, free of charge, to any person\n obtaining a copy of this software and associated documentation files\n (the \"Software\"), to deal in the Software without restriction,\n including without limitation the rights to use, copy, modify, merge,\n publish, distribute, sublicense, and/or sell copies of the Software,\n and to permit persons to whom the Software is furnished to do so,\n subject to the following conditions:\n\n The above copyright notice and this permission notice shall be\n included in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n*/\n\n'use strict';\n\nvar Pattern = require('./pattern').Pattern;\n\n\nvar template_names = {\n django: false,\n erb: false,\n handlebars: false,\n php: false,\n smarty: false\n};\n\n// This lets templates appear anywhere we would do a readUntil\n// The cost is higher but it is pay to play.\nfunction TemplatablePattern(input_scanner, parent) {\n Pattern.call(this, input_scanner, parent);\n this.__template_pattern = null;\n this._disabled = Object.assign({}, template_names);\n this._excluded = Object.assign({}, template_names);\n\n if (parent) {\n this.__template_pattern = this._input.get_regexp(parent.__template_pattern);\n this._excluded = Object.assign(this._excluded, parent._excluded);\n this._disabled = Object.assign(this._disabled, parent._disabled);\n }\n var pattern = new Pattern(input_scanner);\n this.__patterns = {\n handlebars_comment: pattern.starting_with(/{{!--/).until_after(/--}}/),\n handlebars_unescaped: pattern.starting_with(/{{{/).until_after(/}}}/),\n handlebars: pattern.starting_with(/{{/).until_after(/}}/),\n php: pattern.starting_with(/<\\?(?:[= ]|php)/).until_after(/\\?>/),\n erb: pattern.starting_with(/<%[^%]/).until_after(/[^%]%>/),\n // django coflicts with handlebars a bit.\n django: pattern.starting_with(/{%/).until_after(/%}/),\n django_value: pattern.starting_with(/{{/).until_after(/}}/),\n django_comment: pattern.starting_with(/{#/).until_after(/#}/),\n smarty: pattern.starting_with(/{(?=[^}{\\s\\n])/).until_after(/[^\\s\\n]}/),\n smarty_comment: pattern.starting_with(/{\\*/).until_after(/\\*}/),\n smarty_literal: pattern.starting_with(/{literal}/).until_after(/{\\/literal}/)\n };\n}\nTemplatablePattern.prototype = new Pattern();\n\nTemplatablePattern.prototype._create = function() {\n return new TemplatablePattern(this._input, this);\n};\n\nTemplatablePattern.prototype._update = function() {\n this.__set_templated_pattern();\n};\n\nTemplatablePattern.prototype.disable = function(language) {\n var result = this._create();\n result._disabled[language] = true;\n result._update();\n return result;\n};\n\nTemplatablePattern.prototype.read_options = function(options) {\n var result = this._create();\n for (var language in template_names) {\n result._disabled[language] = options.templating.indexOf(language) === -1;\n }\n result._update();\n return result;\n};\n\nTemplatablePattern.prototype.exclude = function(language) {\n var result = this._create();\n result._excluded[language] = true;\n result._update();\n return result;\n};\n\nTemplatablePattern.prototype.read = function() {\n var result = '';\n if (this._match_pattern) {\n result = this._input.read(this._starting_pattern);\n } else {\n result = this._input.read(this._starting_pattern, this.__template_pattern);\n }\n var next = this._read_template();\n while (next) {\n if (this._match_pattern) {\n next += this._input.read(this._match_pattern);\n } else {\n next += this._input.readUntil(this.__template_pattern);\n }\n result += next;\n next = this._read_template();\n }\n\n if (this._until_after) {\n result += this._input.readUntilAfter(this._until_pattern);\n }\n return result;\n};\n\nTemplatablePattern.prototype.__set_templated_pattern = function() {\n var items = [];\n\n if (!this._disabled.php) {\n items.push(this.__patterns.php._starting_pattern.source);\n }\n if (!this._disabled.handlebars) {\n items.push(this.__patterns.handlebars._starting_pattern.source);\n }\n if (!this._disabled.erb) {\n items.push(this.__patterns.erb._starting_pattern.source);\n }\n if (!this._disabled.django) {\n items.push(this.__patterns.django._starting_pattern.source);\n // The starting pattern for django is more complex because it has different\n // patterns for value, comment, and other sections\n items.push(this.__patterns.django_value._starting_pattern.source);\n items.push(this.__patterns.django_comment._starting_pattern.source);\n }\n if (!this._disabled.smarty) {\n items.push(this.__patterns.smarty._starting_pattern.source);\n }\n\n if (this._until_pattern) {\n items.push(this._until_pattern.source);\n }\n this.__template_pattern = this._input.get_regexp('(?:' + items.join('|') + ')');\n};\n\nTemplatablePattern.prototype._read_template = function() {\n var resulting_string = '';\n var c = this._input.peek();\n if (c === '<') {\n var peek1 = this._input.peek(1);\n //if we're in a comment, do something special\n // We treat all comments as literals, even more than preformatted tags\n // we just look for the appropriate close tag\n if (!this._disabled.php && !this._excluded.php && peek1 === '?') {\n resulting_string = resulting_string ||\n this.__patterns.php.read();\n }\n if (!this._disabled.erb && !this._excluded.erb && peek1 === '%') {\n resulting_string = resulting_string ||\n this.__patterns.erb.read();\n }\n } else if (c === '{') {\n if (!this._disabled.handlebars && !this._excluded.handlebars) {\n resulting_string = resulting_string ||\n this.__patterns.handlebars_comment.read();\n resulting_string = resulting_string ||\n this.__patterns.handlebars_unescaped.read();\n resulting_string = resulting_string ||\n this.__patterns.handlebars.read();\n }\n if (!this._disabled.django) {\n // django coflicts with handlebars a bit.\n if (!this._excluded.django && !this._excluded.handlebars) {\n resulting_string = resulting_string ||\n this.__patterns.django_value.read();\n }\n if (!this._excluded.django) {\n resulting_string = resulting_string ||\n this.__patterns.django_comment.read();\n resulting_string = resulting_string ||\n this.__patterns.django.read();\n }\n }\n if (!this._disabled.smarty) {\n // smarty cannot be enabled with django or handlebars enabled\n if (this._disabled.django && this._disabled.handlebars) {\n resulting_string = resulting_string ||\n this.__patterns.smarty_comment.read();\n resulting_string = resulting_string ||\n this.__patterns.smarty_literal.read();\n resulting_string = resulting_string ||\n this.__patterns.smarty.read();\n }\n }\n }\n return resulting_string;\n};\n\n\nmodule.exports.TemplatablePattern = TemplatablePattern;\n","/*jshint node:true */\n/*\n\n The MIT License (MIT)\n\n Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.\n\n Permission is hereby granted, free of charge, to any person\n obtaining a copy of this software and associated documentation files\n (the \"Software\"), to deal in the Software without restriction,\n including without limitation the rights to use, copy, modify, merge,\n publish, distribute, sublicense, and/or sell copies of the Software,\n and to permit persons to whom the Software is furnished to do so,\n subject to the following conditions:\n\n The above copyright notice and this permission notice shall be\n included in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n*/\n\n'use strict';\n\nvar InputScanner = require('../core/inputscanner').InputScanner;\nvar BaseTokenizer = require('../core/tokenizer').Tokenizer;\nvar BASETOKEN = require('../core/tokenizer').TOKEN;\nvar Directives = require('../core/directives').Directives;\nvar acorn = require('./acorn');\nvar Pattern = require('../core/pattern').Pattern;\nvar TemplatablePattern = require('../core/templatablepattern').TemplatablePattern;\n\n\nfunction in_array(what, arr) {\n return arr.indexOf(what) !== -1;\n}\n\n\nvar TOKEN = {\n START_EXPR: 'TK_START_EXPR',\n END_EXPR: 'TK_END_EXPR',\n START_BLOCK: 'TK_START_BLOCK',\n END_BLOCK: 'TK_END_BLOCK',\n WORD: 'TK_WORD',\n RESERVED: 'TK_RESERVED',\n SEMICOLON: 'TK_SEMICOLON',\n STRING: 'TK_STRING',\n EQUALS: 'TK_EQUALS',\n OPERATOR: 'TK_OPERATOR',\n COMMA: 'TK_COMMA',\n BLOCK_COMMENT: 'TK_BLOCK_COMMENT',\n COMMENT: 'TK_COMMENT',\n DOT: 'TK_DOT',\n UNKNOWN: 'TK_UNKNOWN',\n START: BASETOKEN.START,\n RAW: BASETOKEN.RAW,\n EOF: BASETOKEN.EOF\n};\n\n\nvar directives_core = new Directives(/\\/\\*/, /\\*\\//);\n\nvar number_pattern = /0[xX][0123456789abcdefABCDEF_]*n?|0[oO][01234567_]*n?|0[bB][01_]*n?|\\d[\\d_]*n|(?:\\.\\d[\\d_]*|\\d[\\d_]*\\.?[\\d_]*)(?:[eE][+-]?[\\d_]+)?/;\n\nvar digit = /[0-9]/;\n\n// Dot \".\" must be distinguished from \"...\" and decimal\nvar dot_pattern = /[^\\d\\.]/;\n\nvar positionable_operators = (\n \">>> === !== &&= ??= ||= \" +\n \"<< && >= ** != == <= >> || ?? |> \" +\n \"< / - + > : & % ? ^ | *\").split(' ');\n\n// IMPORTANT: this must be sorted longest to shortest or tokenizing many not work.\n// Also, you must update possitionable operators separately from punct\nvar punct =\n \">>>= \" +\n \"... >>= <<= === >>> !== **= &&= ??= ||= \" +\n \"=> ^= :: /= << <= == && -= >= >> != -- += ** || ?? ++ %= &= *= |= |> \" +\n \"= ! ? > < : / ^ - + * & % ~ |\";\n\npunct = punct.replace(/[-[\\]{}()*+?.,\\\\^$|#]/g, \"\\\\$&\");\n// ?. but not if followed by a number \npunct = '\\\\?\\\\.(?!\\\\d) ' + punct;\npunct = punct.replace(/ /g, '|');\n\nvar punct_pattern = new RegExp(punct);\n\n// words which should always start on new line.\nvar line_starters = 'continue,try,throw,return,var,let,const,if,switch,case,default,for,while,break,function,import,export'.split(',');\nvar reserved_words = line_starters.concat(['do', 'in', 'of', 'else', 'get', 'set', 'new', 'catch', 'finally', 'typeof', 'yield', 'async', 'await', 'from', 'as', 'class', 'extends']);\nvar reserved_word_pattern = new RegExp('^(?:' + reserved_words.join('|') + ')$');\n\n// var template_pattern = /(?:(?:<\\?php|<\\?=)[\\s\\S]*?\\?>)|(?:<%[\\s\\S]*?%>)/g;\n\nvar in_html_comment;\n\nvar Tokenizer = function(input_string, options) {\n BaseTokenizer.call(this, input_string, options);\n\n this._patterns.whitespace = this._patterns.whitespace.matching(\n /\\u00A0\\u1680\\u180e\\u2000-\\u200a\\u202f\\u205f\\u3000\\ufeff/.source,\n /\\u2028\\u2029/.source);\n\n var pattern_reader = new Pattern(this._input);\n var templatable = new TemplatablePattern(this._input)\n .read_options(this._options);\n\n this.__patterns = {\n template: templatable,\n identifier: templatable.starting_with(acorn.identifier).matching(acorn.identifierMatch),\n number: pattern_reader.matching(number_pattern),\n punct: pattern_reader.matching(punct_pattern),\n // comment ends just before nearest linefeed or end of file\n comment: pattern_reader.starting_with(/\\/\\//).until(/[\\n\\r\\u2028\\u2029]/),\n // /* ... */ comment ends with nearest */ or end of file\n block_comment: pattern_reader.starting_with(/\\/\\*/).until_after(/\\*\\//),\n html_comment_start: pattern_reader.matching(//),\n include: pattern_reader.starting_with(/#include/).until_after(acorn.lineBreak),\n shebang: pattern_reader.starting_with(/#!/).until_after(acorn.lineBreak),\n xml: pattern_reader.matching(/[\\s\\S]*?<(\\/?)([-a-zA-Z:0-9_.]+|{[^}]+?}|!\\[CDATA\\[[^\\]]*?\\]\\]|)(\\s*{[^}]+?}|\\s+[-a-zA-Z:0-9_.]+|\\s+[-a-zA-Z:0-9_.]+\\s*=\\s*('[^']*'|\"[^\"]*\"|{([^{}]|{[^}]+?})+?}))*\\s*(\\/?)\\s*>/),\n single_quote: templatable.until(/['\\\\\\n\\r\\u2028\\u2029]/),\n double_quote: templatable.until(/[\"\\\\\\n\\r\\u2028\\u2029]/),\n template_text: templatable.until(/[`\\\\$]/),\n template_expression: templatable.until(/[`}\\\\]/)\n };\n\n};\nTokenizer.prototype = new BaseTokenizer();\n\nTokenizer.prototype._is_comment = function(current_token) {\n return current_token.type === TOKEN.COMMENT || current_token.type === TOKEN.BLOCK_COMMENT || current_token.type === TOKEN.UNKNOWN;\n};\n\nTokenizer.prototype._is_opening = function(current_token) {\n return current_token.type === TOKEN.START_BLOCK || current_token.type === TOKEN.START_EXPR;\n};\n\nTokenizer.prototype._is_closing = function(current_token, open_token) {\n return (current_token.type === TOKEN.END_BLOCK || current_token.type === TOKEN.END_EXPR) &&\n (open_token && (\n (current_token.text === ']' && open_token.text === '[') ||\n (current_token.text === ')' && open_token.text === '(') ||\n (current_token.text === '}' && open_token.text === '{')));\n};\n\nTokenizer.prototype._reset = function() {\n in_html_comment = false;\n};\n\nTokenizer.prototype._get_next_token = function(previous_token, open_token) { // jshint unused:false\n var token = null;\n this._readWhitespace();\n var c = this._input.peek();\n\n if (c === null) {\n return this._create_token(TOKEN.EOF, '');\n }\n\n token = token || this._read_non_javascript(c);\n token = token || this._read_string(c);\n token = token || this._read_word(previous_token);\n token = token || this._read_singles(c);\n token = token || this._read_comment(c);\n token = token || this._read_regexp(c, previous_token);\n token = token || this._read_xml(c, previous_token);\n token = token || this._read_punctuation();\n token = token || this._create_token(TOKEN.UNKNOWN, this._input.next());\n\n return token;\n};\n\nTokenizer.prototype._read_word = function(previous_token) {\n var resulting_string;\n resulting_string = this.__patterns.identifier.read();\n if (resulting_string !== '') {\n resulting_string = resulting_string.replace(acorn.allLineBreaks, '\\n');\n if (!(previous_token.type === TOKEN.DOT ||\n (previous_token.type === TOKEN.RESERVED && (previous_token.text === 'set' || previous_token.text === 'get'))) &&\n reserved_word_pattern.test(resulting_string)) {\n if ((resulting_string === 'in' || resulting_string === 'of') &&\n (previous_token.type === TOKEN.WORD || previous_token.type === TOKEN.STRING)) { // hack for 'in' and 'of' operators\n return this._create_token(TOKEN.OPERATOR, resulting_string);\n }\n return this._create_token(TOKEN.RESERVED, resulting_string);\n }\n return this._create_token(TOKEN.WORD, resulting_string);\n }\n\n resulting_string = this.__patterns.number.read();\n if (resulting_string !== '') {\n return this._create_token(TOKEN.WORD, resulting_string);\n }\n};\n\nTokenizer.prototype._read_singles = function(c) {\n var token = null;\n if (c === '(' || c === '[') {\n token = this._create_token(TOKEN.START_EXPR, c);\n } else if (c === ')' || c === ']') {\n token = this._create_token(TOKEN.END_EXPR, c);\n } else if (c === '{') {\n token = this._create_token(TOKEN.START_BLOCK, c);\n } else if (c === '}') {\n token = this._create_token(TOKEN.END_BLOCK, c);\n } else if (c === ';') {\n token = this._create_token(TOKEN.SEMICOLON, c);\n } else if (c === '.' && dot_pattern.test(this._input.peek(1))) {\n token = this._create_token(TOKEN.DOT, c);\n } else if (c === ',') {\n token = this._create_token(TOKEN.COMMA, c);\n }\n\n if (token) {\n this._input.next();\n }\n return token;\n};\n\nTokenizer.prototype._read_punctuation = function() {\n var resulting_string = this.__patterns.punct.read();\n\n if (resulting_string !== '') {\n if (resulting_string === '=') {\n return this._create_token(TOKEN.EQUALS, resulting_string);\n } else if (resulting_string === '?.') {\n return this._create_token(TOKEN.DOT, resulting_string);\n } else {\n return this._create_token(TOKEN.OPERATOR, resulting_string);\n }\n }\n};\n\nTokenizer.prototype._read_non_javascript = function(c) {\n var resulting_string = '';\n\n if (c === '#') {\n if (this._is_first_token()) {\n resulting_string = this.__patterns.shebang.read();\n\n if (resulting_string) {\n return this._create_token(TOKEN.UNKNOWN, resulting_string.trim() + '\\n');\n }\n }\n\n // handles extendscript #includes\n resulting_string = this.__patterns.include.read();\n\n if (resulting_string) {\n return this._create_token(TOKEN.UNKNOWN, resulting_string.trim() + '\\n');\n }\n\n c = this._input.next();\n\n // Spidermonkey-specific sharp variables for circular references. Considered obsolete.\n var sharp = '#';\n if (this._input.hasNext() && this._input.testChar(digit)) {\n do {\n c = this._input.next();\n sharp += c;\n } while (this._input.hasNext() && c !== '#' && c !== '=');\n if (c === '#') {\n //\n } else if (this._input.peek() === '[' && this._input.peek(1) === ']') {\n sharp += '[]';\n this._input.next();\n this._input.next();\n } else if (this._input.peek() === '{' && this._input.peek(1) === '}') {\n sharp += '{}';\n this._input.next();\n this._input.next();\n }\n return this._create_token(TOKEN.WORD, sharp);\n }\n\n this._input.back();\n\n } else if (c === '<' && this._is_first_token()) {\n resulting_string = this.__patterns.html_comment_start.read();\n if (resulting_string) {\n while (this._input.hasNext() && !this._input.testChar(acorn.newline)) {\n resulting_string += this._input.next();\n }\n in_html_comment = true;\n return this._create_token(TOKEN.COMMENT, resulting_string);\n }\n } else if (in_html_comment && c === '-') {\n resulting_string = this.__patterns.html_comment_end.read();\n if (resulting_string) {\n in_html_comment = false;\n return this._create_token(TOKEN.COMMENT, resulting_string);\n }\n }\n\n return null;\n};\n\nTokenizer.prototype._read_comment = function(c) {\n var token = null;\n if (c === '/') {\n var comment = '';\n if (this._input.peek(1) === '*') {\n // peek for comment /* ... */\n comment = this.__patterns.block_comment.read();\n var directives = directives_core.get_directives(comment);\n if (directives && directives.ignore === 'start') {\n comment += directives_core.readIgnored(this._input);\n }\n comment = comment.replace(acorn.allLineBreaks, '\\n');\n token = this._create_token(TOKEN.BLOCK_COMMENT, comment);\n token.directives = directives;\n } else if (this._input.peek(1) === '/') {\n // peek for comment // ...\n comment = this.__patterns.comment.read();\n token = this._create_token(TOKEN.COMMENT, comment);\n }\n }\n return token;\n};\n\nTokenizer.prototype._read_string = function(c) {\n if (c === '`' || c === \"'\" || c === '\"') {\n var resulting_string = this._input.next();\n this.has_char_escapes = false;\n\n if (c === '`') {\n resulting_string += this._read_string_recursive('`', true, '${');\n } else {\n resulting_string += this._read_string_recursive(c);\n }\n\n if (this.has_char_escapes && this._options.unescape_strings) {\n resulting_string = unescape_string(resulting_string);\n }\n\n if (this._input.peek() === c) {\n resulting_string += this._input.next();\n }\n\n resulting_string = resulting_string.replace(acorn.allLineBreaks, '\\n');\n\n return this._create_token(TOKEN.STRING, resulting_string);\n }\n\n return null;\n};\n\nTokenizer.prototype._allow_regexp_or_xml = function(previous_token) {\n // regex and xml can only appear in specific locations during parsing\n return (previous_token.type === TOKEN.RESERVED && in_array(previous_token.text, ['return', 'case', 'throw', 'else', 'do', 'typeof', 'yield'])) ||\n (previous_token.type === TOKEN.END_EXPR && previous_token.text === ')' &&\n previous_token.opened.previous.type === TOKEN.RESERVED && in_array(previous_token.opened.previous.text, ['if', 'while', 'for'])) ||\n (in_array(previous_token.type, [TOKEN.COMMENT, TOKEN.START_EXPR, TOKEN.START_BLOCK, TOKEN.START,\n TOKEN.END_BLOCK, TOKEN.OPERATOR, TOKEN.EQUALS, TOKEN.EOF, TOKEN.SEMICOLON, TOKEN.COMMA\n ]));\n};\n\nTokenizer.prototype._read_regexp = function(c, previous_token) {\n\n if (c === '/' && this._allow_regexp_or_xml(previous_token)) {\n // handle regexp\n //\n var resulting_string = this._input.next();\n var esc = false;\n\n var in_char_class = false;\n while (this._input.hasNext() &&\n ((esc || in_char_class || this._input.peek() !== c) &&\n !this._input.testChar(acorn.newline))) {\n resulting_string += this._input.peek();\n if (!esc) {\n esc = this._input.peek() === '\\\\';\n if (this._input.peek() === '[') {\n in_char_class = true;\n } else if (this._input.peek() === ']') {\n in_char_class = false;\n }\n } else {\n esc = false;\n }\n this._input.next();\n }\n\n if (this._input.peek() === c) {\n resulting_string += this._input.next();\n\n // regexps may have modifiers /regexp/MOD , so fetch those, too\n // Only [gim] are valid, but if the user puts in garbage, do what we can to take it.\n resulting_string += this._input.read(acorn.identifier);\n }\n return this._create_token(TOKEN.STRING, resulting_string);\n }\n return null;\n};\n\nTokenizer.prototype._read_xml = function(c, previous_token) {\n\n if (this._options.e4x && c === \"<\" && this._allow_regexp_or_xml(previous_token)) {\n var xmlStr = '';\n var match = this.__patterns.xml.read_match();\n // handle e4x xml literals\n //\n if (match) {\n // Trim root tag to attempt to\n var rootTag = match[2].replace(/^{\\s+/, '{').replace(/\\s+}$/, '}');\n var isCurlyRoot = rootTag.indexOf('{') === 0;\n var depth = 0;\n while (match) {\n var isEndTag = !!match[1];\n var tagName = match[2];\n var isSingletonTag = (!!match[match.length - 1]) || (tagName.slice(0, 8) === \"![CDATA[\");\n if (!isSingletonTag &&\n (tagName === rootTag || (isCurlyRoot && tagName.replace(/^{\\s+/, '{').replace(/\\s+}$/, '}')))) {\n if (isEndTag) {\n --depth;\n } else {\n ++depth;\n }\n }\n xmlStr += match[0];\n if (depth <= 0) {\n break;\n }\n match = this.__patterns.xml.read_match();\n }\n // if we didn't close correctly, keep unformatted.\n if (!match) {\n xmlStr += this._input.match(/[\\s\\S]*/g)[0];\n }\n xmlStr = xmlStr.replace(acorn.allLineBreaks, '\\n');\n return this._create_token(TOKEN.STRING, xmlStr);\n }\n }\n\n return null;\n};\n\nfunction unescape_string(s) {\n // You think that a regex would work for this\n // return s.replace(/\\\\x([0-9a-f]{2})/gi, function(match, val) {\n // return String.fromCharCode(parseInt(val, 16));\n // })\n // However, dealing with '\\xff', '\\\\xff', '\\\\\\xff' makes this more fun.\n var out = '',\n escaped = 0;\n\n var input_scan = new InputScanner(s);\n var matched = null;\n\n while (input_scan.hasNext()) {\n // Keep any whitespace, non-slash characters\n // also keep slash pairs.\n matched = input_scan.match(/([\\s]|[^\\\\]|\\\\\\\\)+/g);\n\n if (matched) {\n out += matched[0];\n }\n\n if (input_scan.peek() === '\\\\') {\n input_scan.next();\n if (input_scan.peek() === 'x') {\n matched = input_scan.match(/x([0-9A-Fa-f]{2})/g);\n } else if (input_scan.peek() === 'u') {\n matched = input_scan.match(/u([0-9A-Fa-f]{4})/g);\n } else {\n out += '\\\\';\n if (input_scan.hasNext()) {\n out += input_scan.next();\n }\n continue;\n }\n\n // If there's some error decoding, return the original string\n if (!matched) {\n return s;\n }\n\n escaped = parseInt(matched[1], 16);\n\n if (escaped > 0x7e && escaped <= 0xff && matched[0].indexOf('x') === 0) {\n // we bail out on \\x7f..\\xff,\n // leaving whole string escaped,\n // as it's probably completely binary\n return s;\n } else if (escaped >= 0x00 && escaped < 0x20) {\n // leave 0x00...0x1f escaped\n out += '\\\\' + matched[0];\n continue;\n } else if (escaped === 0x22 || escaped === 0x27 || escaped === 0x5c) {\n // single-quote, apostrophe, backslash - escape these\n out += '\\\\' + String.fromCharCode(escaped);\n } else {\n out += String.fromCharCode(escaped);\n }\n }\n }\n\n return out;\n}\n\n// handle string\n//\nTokenizer.prototype._read_string_recursive = function(delimiter, allow_unescaped_newlines, start_sub) {\n var current_char;\n var pattern;\n if (delimiter === '\\'') {\n pattern = this.__patterns.single_quote;\n } else if (delimiter === '\"') {\n pattern = this.__patterns.double_quote;\n } else if (delimiter === '`') {\n pattern = this.__patterns.template_text;\n } else if (delimiter === '}') {\n pattern = this.__patterns.template_expression;\n }\n\n var resulting_string = pattern.read();\n var next = '';\n while (this._input.hasNext()) {\n next = this._input.next();\n if (next === delimiter ||\n (!allow_unescaped_newlines && acorn.newline.test(next))) {\n this._input.back();\n break;\n } else if (next === '\\\\' && this._input.hasNext()) {\n current_char = this._input.peek();\n\n if (current_char === 'x' || current_char === 'u') {\n this.has_char_escapes = true;\n } else if (current_char === '\\r' && this._input.peek(1) === '\\n') {\n this._input.next();\n }\n next += this._input.next();\n } else if (start_sub) {\n if (start_sub === '${' && next === '$' && this._input.peek() === '{') {\n next += this._input.next();\n }\n\n if (start_sub === next) {\n if (delimiter === '`') {\n next += this._read_string_recursive('}', allow_unescaped_newlines, '`');\n } else {\n next += this._read_string_recursive('`', allow_unescaped_newlines, '${');\n }\n if (this._input.hasNext()) {\n next += this._input.next();\n }\n }\n }\n next += pattern.read();\n resulting_string += next;\n }\n\n return resulting_string;\n};\n\nmodule.exports.Tokenizer = Tokenizer;\nmodule.exports.TOKEN = TOKEN;\nmodule.exports.positionable_operators = positionable_operators.slice();\nmodule.exports.line_starters = line_starters.slice();\n","/*jshint node:true */\n/*\n\n The MIT License (MIT)\n\n Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.\n\n Permission is hereby granted, free of charge, to any person\n obtaining a copy of this software and associated documentation files\n (the \"Software\"), to deal in the Software without restriction,\n including without limitation the rights to use, copy, modify, merge,\n publish, distribute, sublicense, and/or sell copies of the Software,\n and to permit persons to whom the Software is furnished to do so,\n subject to the following conditions:\n\n The above copyright notice and this permission notice shall be\n included in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n*/\n\n'use strict';\n\nvar Output = require('../core/output').Output;\nvar Token = require('../core/token').Token;\nvar acorn = require('./acorn');\nvar Options = require('./options').Options;\nvar Tokenizer = require('./tokenizer').Tokenizer;\nvar line_starters = require('./tokenizer').line_starters;\nvar positionable_operators = require('./tokenizer').positionable_operators;\nvar TOKEN = require('./tokenizer').TOKEN;\n\n\nfunction in_array(what, arr) {\n return arr.indexOf(what) !== -1;\n}\n\nfunction ltrim(s) {\n return s.replace(/^\\s+/g, '');\n}\n\nfunction generateMapFromStrings(list) {\n var result = {};\n for (var x = 0; x < list.length; x++) {\n // make the mapped names underscored instead of dash\n result[list[x].replace(/-/g, '_')] = list[x];\n }\n return result;\n}\n\nfunction reserved_word(token, word) {\n return token && token.type === TOKEN.RESERVED && token.text === word;\n}\n\nfunction reserved_array(token, words) {\n return token && token.type === TOKEN.RESERVED && in_array(token.text, words);\n}\n// Unsure of what they mean, but they work. Worth cleaning up in future.\nvar special_words = ['case', 'return', 'do', 'if', 'throw', 'else', 'await', 'break', 'continue', 'async'];\n\nvar validPositionValues = ['before-newline', 'after-newline', 'preserve-newline'];\n\n// Generate map from array\nvar OPERATOR_POSITION = generateMapFromStrings(validPositionValues);\n\nvar OPERATOR_POSITION_BEFORE_OR_PRESERVE = [OPERATOR_POSITION.before_newline, OPERATOR_POSITION.preserve_newline];\n\nvar MODE = {\n BlockStatement: 'BlockStatement', // 'BLOCK'\n Statement: 'Statement', // 'STATEMENT'\n ObjectLiteral: 'ObjectLiteral', // 'OBJECT',\n ArrayLiteral: 'ArrayLiteral', //'[EXPRESSION]',\n ForInitializer: 'ForInitializer', //'(FOR-EXPRESSION)',\n Conditional: 'Conditional', //'(COND-EXPRESSION)',\n Expression: 'Expression' //'(EXPRESSION)'\n};\n\nfunction remove_redundant_indentation(output, frame) {\n // This implementation is effective but has some issues:\n // - can cause line wrap to happen too soon due to indent removal\n // after wrap points are calculated\n // These issues are minor compared to ugly indentation.\n\n if (frame.multiline_frame ||\n frame.mode === MODE.ForInitializer ||\n frame.mode === MODE.Conditional) {\n return;\n }\n\n // remove one indent from each line inside this section\n output.remove_indent(frame.start_line_index);\n}\n\n// we could use just string.split, but\n// IE doesn't like returning empty strings\nfunction split_linebreaks(s) {\n //return s.split(/\\x0d\\x0a|\\x0a/);\n\n s = s.replace(acorn.allLineBreaks, '\\n');\n var out = [],\n idx = s.indexOf(\"\\n\");\n while (idx !== -1) {\n out.push(s.substring(0, idx));\n s = s.substring(idx + 1);\n idx = s.indexOf(\"\\n\");\n }\n if (s.length) {\n out.push(s);\n }\n return out;\n}\n\nfunction is_array(mode) {\n return mode === MODE.ArrayLiteral;\n}\n\nfunction is_expression(mode) {\n return in_array(mode, [MODE.Expression, MODE.ForInitializer, MODE.Conditional]);\n}\n\nfunction all_lines_start_with(lines, c) {\n for (var i = 0; i < lines.length; i++) {\n var line = lines[i].trim();\n if (line.charAt(0) !== c) {\n return false;\n }\n }\n return true;\n}\n\nfunction each_line_matches_indent(lines, indent) {\n var i = 0,\n len = lines.length,\n line;\n for (; i < len; i++) {\n line = lines[i];\n // allow empty lines to pass through\n if (line && line.indexOf(indent) !== 0) {\n return false;\n }\n }\n return true;\n}\n\n\nfunction Beautifier(source_text, options) {\n options = options || {};\n this._source_text = source_text || '';\n\n this._output = null;\n this._tokens = null;\n this._last_last_text = null;\n this._flags = null;\n this._previous_flags = null;\n\n this._flag_store = null;\n this._options = new Options(options);\n}\n\nBeautifier.prototype.create_flags = function(flags_base, mode) {\n var next_indent_level = 0;\n if (flags_base) {\n next_indent_level = flags_base.indentation_level;\n if (!this._output.just_added_newline() &&\n flags_base.line_indent_level > next_indent_level) {\n next_indent_level = flags_base.line_indent_level;\n }\n }\n\n var next_flags = {\n mode: mode,\n parent: flags_base,\n last_token: flags_base ? flags_base.last_token : new Token(TOKEN.START_BLOCK, ''), // last token text\n last_word: flags_base ? flags_base.last_word : '', // last TOKEN.WORD passed\n declaration_statement: false,\n declaration_assignment: false,\n multiline_frame: false,\n inline_frame: false,\n if_block: false,\n else_block: false,\n class_start_block: false, // class A { INSIDE HERE } or class B extends C { INSIDE HERE }\n do_block: false,\n do_while: false,\n import_block: false,\n in_case_statement: false, // switch(..){ INSIDE HERE }\n in_case: false, // we're on the exact line with \"case 0:\"\n case_body: false, // the indented case-action block\n case_block: false, // the indented case-action block is wrapped with {}\n indentation_level: next_indent_level,\n alignment: 0,\n line_indent_level: flags_base ? flags_base.line_indent_level : next_indent_level,\n start_line_index: this._output.get_line_number(),\n ternary_depth: 0\n };\n return next_flags;\n};\n\nBeautifier.prototype._reset = function(source_text) {\n var baseIndentString = source_text.match(/^[\\t ]*/)[0];\n\n this._last_last_text = ''; // pre-last token text\n this._output = new Output(this._options, baseIndentString);\n\n // If testing the ignore directive, start with output disable set to true\n this._output.raw = this._options.test_output_raw;\n\n\n // Stack of parsing/formatting states, including MODE.\n // We tokenize, parse, and output in an almost purely a forward-only stream of token input\n // and formatted output. This makes the beautifier less accurate than full parsers\n // but also far more tolerant of syntax errors.\n //\n // For example, the default mode is MODE.BlockStatement. If we see a '{' we push a new frame of type\n // MODE.BlockStatement on the the stack, even though it could be object literal. If we later\n // encounter a \":\", we'll switch to to MODE.ObjectLiteral. If we then see a \";\",\n // most full parsers would die, but the beautifier gracefully falls back to\n // MODE.BlockStatement and continues on.\n this._flag_store = [];\n this.set_mode(MODE.BlockStatement);\n var tokenizer = new Tokenizer(source_text, this._options);\n this._tokens = tokenizer.tokenize();\n return source_text;\n};\n\nBeautifier.prototype.beautify = function() {\n // if disabled, return the input unchanged.\n if (this._options.disabled) {\n return this._source_text;\n }\n\n var sweet_code;\n var source_text = this._reset(this._source_text);\n\n var eol = this._options.eol;\n if (this._options.eol === 'auto') {\n eol = '\\n';\n if (source_text && acorn.lineBreak.test(source_text || '')) {\n eol = source_text.match(acorn.lineBreak)[0];\n }\n }\n\n var current_token = this._tokens.next();\n while (current_token) {\n this.handle_token(current_token);\n\n this._last_last_text = this._flags.last_token.text;\n this._flags.last_token = current_token;\n\n current_token = this._tokens.next();\n }\n\n sweet_code = this._output.get_code(eol);\n\n return sweet_code;\n};\n\nBeautifier.prototype.handle_token = function(current_token, preserve_statement_flags) {\n if (current_token.type === TOKEN.START_EXPR) {\n this.handle_start_expr(current_token);\n } else if (current_token.type === TOKEN.END_EXPR) {\n this.handle_end_expr(current_token);\n } else if (current_token.type === TOKEN.START_BLOCK) {\n this.handle_start_block(current_token);\n } else if (current_token.type === TOKEN.END_BLOCK) {\n this.handle_end_block(current_token);\n } else if (current_token.type === TOKEN.WORD) {\n this.handle_word(current_token);\n } else if (current_token.type === TOKEN.RESERVED) {\n this.handle_word(current_token);\n } else if (current_token.type === TOKEN.SEMICOLON) {\n this.handle_semicolon(current_token);\n } else if (current_token.type === TOKEN.STRING) {\n this.handle_string(current_token);\n } else if (current_token.type === TOKEN.EQUALS) {\n this.handle_equals(current_token);\n } else if (current_token.type === TOKEN.OPERATOR) {\n this.handle_operator(current_token);\n } else if (current_token.type === TOKEN.COMMA) {\n this.handle_comma(current_token);\n } else if (current_token.type === TOKEN.BLOCK_COMMENT) {\n this.handle_block_comment(current_token, preserve_statement_flags);\n } else if (current_token.type === TOKEN.COMMENT) {\n this.handle_comment(current_token, preserve_statement_flags);\n } else if (current_token.type === TOKEN.DOT) {\n this.handle_dot(current_token);\n } else if (current_token.type === TOKEN.EOF) {\n this.handle_eof(current_token);\n } else if (current_token.type === TOKEN.UNKNOWN) {\n this.handle_unknown(current_token, preserve_statement_flags);\n } else {\n this.handle_unknown(current_token, preserve_statement_flags);\n }\n};\n\nBeautifier.prototype.handle_whitespace_and_comments = function(current_token, preserve_statement_flags) {\n var newlines = current_token.newlines;\n var keep_whitespace = this._options.keep_array_indentation && is_array(this._flags.mode);\n\n if (current_token.comments_before) {\n var comment_token = current_token.comments_before.next();\n while (comment_token) {\n // The cleanest handling of inline comments is to treat them as though they aren't there.\n // Just continue formatting and the behavior should be logical.\n // Also ignore unknown tokens. Again, this should result in better behavior.\n this.handle_whitespace_and_comments(comment_token, preserve_statement_flags);\n this.handle_token(comment_token, preserve_statement_flags);\n comment_token = current_token.comments_before.next();\n }\n }\n\n if (keep_whitespace) {\n for (var i = 0; i < newlines; i += 1) {\n this.print_newline(i > 0, preserve_statement_flags);\n }\n } else {\n if (this._options.max_preserve_newlines && newlines > this._options.max_preserve_newlines) {\n newlines = this._options.max_preserve_newlines;\n }\n\n if (this._options.preserve_newlines) {\n if (newlines > 1) {\n this.print_newline(false, preserve_statement_flags);\n for (var j = 1; j < newlines; j += 1) {\n this.print_newline(true, preserve_statement_flags);\n }\n }\n }\n }\n\n};\n\nvar newline_restricted_tokens = ['async', 'break', 'continue', 'return', 'throw', 'yield'];\n\nBeautifier.prototype.allow_wrap_or_preserved_newline = function(current_token, force_linewrap) {\n force_linewrap = (force_linewrap === undefined) ? false : force_linewrap;\n\n // Never wrap the first token on a line\n if (this._output.just_added_newline()) {\n return;\n }\n\n var shouldPreserveOrForce = (this._options.preserve_newlines && current_token.newlines) || force_linewrap;\n var operatorLogicApplies = in_array(this._flags.last_token.text, positionable_operators) ||\n in_array(current_token.text, positionable_operators);\n\n if (operatorLogicApplies) {\n var shouldPrintOperatorNewline = (\n in_array(this._flags.last_token.text, positionable_operators) &&\n in_array(this._options.operator_position, OPERATOR_POSITION_BEFORE_OR_PRESERVE)\n ) ||\n in_array(current_token.text, positionable_operators);\n shouldPreserveOrForce = shouldPreserveOrForce && shouldPrintOperatorNewline;\n }\n\n if (shouldPreserveOrForce) {\n this.print_newline(false, true);\n } else if (this._options.wrap_line_length) {\n if (reserved_array(this._flags.last_token, newline_restricted_tokens)) {\n // These tokens should never have a newline inserted\n // between them and the following expression.\n return;\n }\n this._output.set_wrap_point();\n }\n};\n\nBeautifier.prototype.print_newline = function(force_newline, preserve_statement_flags) {\n if (!preserve_statement_flags) {\n if (this._flags.last_token.text !== ';' && this._flags.last_token.text !== ',' && this._flags.last_token.text !== '=' && (this._flags.last_token.type !== TOKEN.OPERATOR || this._flags.last_token.text === '--' || this._flags.last_token.text === '++')) {\n var next_token = this._tokens.peek();\n while (this._flags.mode === MODE.Statement &&\n !(this._flags.if_block && reserved_word(next_token, 'else')) &&\n !this._flags.do_block) {\n this.restore_mode();\n }\n }\n }\n\n if (this._output.add_new_line(force_newline)) {\n this._flags.multiline_frame = true;\n }\n};\n\nBeautifier.prototype.print_token_line_indentation = function(current_token) {\n if (this._output.just_added_newline()) {\n if (this._options.keep_array_indentation &&\n current_token.newlines &&\n (current_token.text === '[' || is_array(this._flags.mode))) {\n this._output.current_line.set_indent(-1);\n this._output.current_line.push(current_token.whitespace_before);\n this._output.space_before_token = false;\n } else if (this._output.set_indent(this._flags.indentation_level, this._flags.alignment)) {\n this._flags.line_indent_level = this._flags.indentation_level;\n }\n }\n};\n\nBeautifier.prototype.print_token = function(current_token) {\n if (this._output.raw) {\n this._output.add_raw_token(current_token);\n return;\n }\n\n if (this._options.comma_first && current_token.previous && current_token.previous.type === TOKEN.COMMA &&\n this._output.just_added_newline()) {\n if (this._output.previous_line.last() === ',') {\n var popped = this._output.previous_line.pop();\n // if the comma was already at the start of the line,\n // pull back onto that line and reprint the indentation\n if (this._output.previous_line.is_empty()) {\n this._output.previous_line.push(popped);\n this._output.trim(true);\n this._output.current_line.pop();\n this._output.trim();\n }\n\n // add the comma in front of the next token\n this.print_token_line_indentation(current_token);\n this._output.add_token(',');\n this._output.space_before_token = true;\n }\n }\n\n this.print_token_line_indentation(current_token);\n this._output.non_breaking_space = true;\n this._output.add_token(current_token.text);\n if (this._output.previous_token_wrapped) {\n this._flags.multiline_frame = true;\n }\n};\n\nBeautifier.prototype.indent = function() {\n this._flags.indentation_level += 1;\n this._output.set_indent(this._flags.indentation_level, this._flags.alignment);\n};\n\nBeautifier.prototype.deindent = function() {\n if (this._flags.indentation_level > 0 &&\n ((!this._flags.parent) || this._flags.indentation_level > this._flags.parent.indentation_level)) {\n this._flags.indentation_level -= 1;\n this._output.set_indent(this._flags.indentation_level, this._flags.alignment);\n }\n};\n\nBeautifier.prototype.set_mode = function(mode) {\n if (this._flags) {\n this._flag_store.push(this._flags);\n this._previous_flags = this._flags;\n } else {\n this._previous_flags = this.create_flags(null, mode);\n }\n\n this._flags = this.create_flags(this._previous_flags, mode);\n this._output.set_indent(this._flags.indentation_level, this._flags.alignment);\n};\n\n\nBeautifier.prototype.restore_mode = function() {\n if (this._flag_store.length > 0) {\n this._previous_flags = this._flags;\n this._flags = this._flag_store.pop();\n if (this._previous_flags.mode === MODE.Statement) {\n remove_redundant_indentation(this._output, this._previous_flags);\n }\n this._output.set_indent(this._flags.indentation_level, this._flags.alignment);\n }\n};\n\nBeautifier.prototype.start_of_object_property = function() {\n return this._flags.parent.mode === MODE.ObjectLiteral && this._flags.mode === MODE.Statement && (\n (this._flags.last_token.text === ':' && this._flags.ternary_depth === 0) || (reserved_array(this._flags.last_token, ['get', 'set'])));\n};\n\nBeautifier.prototype.start_of_statement = function(current_token) {\n var start = false;\n start = start || reserved_array(this._flags.last_token, ['var', 'let', 'const']) && current_token.type === TOKEN.WORD;\n start = start || reserved_word(this._flags.last_token, 'do');\n start = start || (!(this._flags.parent.mode === MODE.ObjectLiteral && this._flags.mode === MODE.Statement)) && reserved_array(this._flags.last_token, newline_restricted_tokens) && !current_token.newlines;\n start = start || reserved_word(this._flags.last_token, 'else') &&\n !(reserved_word(current_token, 'if') && !current_token.comments_before);\n start = start || (this._flags.last_token.type === TOKEN.END_EXPR && (this._previous_flags.mode === MODE.ForInitializer || this._previous_flags.mode === MODE.Conditional));\n start = start || (this._flags.last_token.type === TOKEN.WORD && this._flags.mode === MODE.BlockStatement &&\n !this._flags.in_case &&\n !(current_token.text === '--' || current_token.text === '++') &&\n this._last_last_text !== 'function' &&\n current_token.type !== TOKEN.WORD && current_token.type !== TOKEN.RESERVED);\n start = start || (this._flags.mode === MODE.ObjectLiteral && (\n (this._flags.last_token.text === ':' && this._flags.ternary_depth === 0) || reserved_array(this._flags.last_token, ['get', 'set'])));\n\n if (start) {\n this.set_mode(MODE.Statement);\n this.indent();\n\n this.handle_whitespace_and_comments(current_token, true);\n\n // Issue #276:\n // If starting a new statement with [if, for, while, do], push to a new line.\n // if (a) if (b) if(c) d(); else e(); else f();\n if (!this.start_of_object_property()) {\n this.allow_wrap_or_preserved_newline(current_token,\n reserved_array(current_token, ['do', 'for', 'if', 'while']));\n }\n return true;\n }\n return false;\n};\n\nBeautifier.prototype.handle_start_expr = function(current_token) {\n // The conditional starts the statement if appropriate.\n if (!this.start_of_statement(current_token)) {\n this.handle_whitespace_and_comments(current_token);\n }\n\n var next_mode = MODE.Expression;\n if (current_token.text === '[') {\n\n if (this._flags.last_token.type === TOKEN.WORD || this._flags.last_token.text === ')') {\n // this is array index specifier, break immediately\n // a[x], fn()[x]\n if (reserved_array(this._flags.last_token, line_starters)) {\n this._output.space_before_token = true;\n }\n this.print_token(current_token);\n this.set_mode(next_mode);\n this.indent();\n if (this._options.space_in_paren) {\n this._output.space_before_token = true;\n }\n return;\n }\n\n next_mode = MODE.ArrayLiteral;\n if (is_array(this._flags.mode)) {\n if (this._flags.last_token.text === '[' ||\n (this._flags.last_token.text === ',' && (this._last_last_text === ']' || this._last_last_text === '}'))) {\n // ], [ goes to new line\n // }, [ goes to new line\n if (!this._options.keep_array_indentation) {\n this.print_newline();\n }\n }\n }\n\n if (!in_array(this._flags.last_token.type, [TOKEN.START_EXPR, TOKEN.END_EXPR, TOKEN.WORD, TOKEN.OPERATOR, TOKEN.DOT])) {\n this._output.space_before_token = true;\n }\n } else {\n if (this._flags.last_token.type === TOKEN.RESERVED) {\n if (this._flags.last_token.text === 'for') {\n this._output.space_before_token = this._options.space_before_conditional;\n next_mode = MODE.ForInitializer;\n } else if (in_array(this._flags.last_token.text, ['if', 'while', 'switch'])) {\n this._output.space_before_token = this._options.space_before_conditional;\n next_mode = MODE.Conditional;\n } else if (in_array(this._flags.last_word, ['await', 'async'])) {\n // Should be a space between await and an IIFE, or async and an arrow function\n this._output.space_before_token = true;\n } else if (this._flags.last_token.text === 'import' && current_token.whitespace_before === '') {\n this._output.space_before_token = false;\n } else if (in_array(this._flags.last_token.text, line_starters) || this._flags.last_token.text === 'catch') {\n this._output.space_before_token = true;\n }\n } else if (this._flags.last_token.type === TOKEN.EQUALS || this._flags.last_token.type === TOKEN.OPERATOR) {\n // Support of this kind of newline preservation.\n // a = (b &&\n // (c || d));\n if (!this.start_of_object_property()) {\n this.allow_wrap_or_preserved_newline(current_token);\n }\n } else if (this._flags.last_token.type === TOKEN.WORD) {\n this._output.space_before_token = false;\n\n // function name() vs function name ()\n // function* name() vs function* name ()\n // async name() vs async name ()\n // In ES6, you can also define the method properties of an object\n // var obj = {a: function() {}}\n // It can be abbreviated\n // var obj = {a() {}}\n // var obj = { a() {}} vs var obj = { a () {}}\n // var obj = { * a() {}} vs var obj = { * a () {}}\n var peek_back_two = this._tokens.peek(-3);\n if (this._options.space_after_named_function && peek_back_two) {\n // peek starts at next character so -1 is current token\n var peek_back_three = this._tokens.peek(-4);\n if (reserved_array(peek_back_two, ['async', 'function']) ||\n (peek_back_two.text === '*' && reserved_array(peek_back_three, ['async', 'function']))) {\n this._output.space_before_token = true;\n } else if (this._flags.mode === MODE.ObjectLiteral) {\n if ((peek_back_two.text === '{' || peek_back_two.text === ',') ||\n (peek_back_two.text === '*' && (peek_back_three.text === '{' || peek_back_three.text === ','))) {\n this._output.space_before_token = true;\n }\n } else if (this._flags.parent && this._flags.parent.class_start_block) {\n this._output.space_before_token = true;\n }\n }\n } else {\n // Support preserving wrapped arrow function expressions\n // a.b('c',\n // () => d.e\n // )\n this.allow_wrap_or_preserved_newline(current_token);\n }\n\n // function() vs function ()\n // yield*() vs yield* ()\n // function*() vs function* ()\n if ((this._flags.last_token.type === TOKEN.RESERVED && (this._flags.last_word === 'function' || this._flags.last_word === 'typeof')) ||\n (this._flags.last_token.text === '*' &&\n (in_array(this._last_last_text, ['function', 'yield']) ||\n (this._flags.mode === MODE.ObjectLiteral && in_array(this._last_last_text, ['{', ',']))))) {\n this._output.space_before_token = this._options.space_after_anon_function;\n }\n }\n\n if (this._flags.last_token.text === ';' || this._flags.last_token.type === TOKEN.START_BLOCK) {\n this.print_newline();\n } else if (this._flags.last_token.type === TOKEN.END_EXPR || this._flags.last_token.type === TOKEN.START_EXPR || this._flags.last_token.type === TOKEN.END_BLOCK || this._flags.last_token.text === '.' || this._flags.last_token.type === TOKEN.COMMA) {\n // do nothing on (( and )( and ][ and ]( and .(\n // TODO: Consider whether forcing this is required. Review failing tests when removed.\n this.allow_wrap_or_preserved_newline(current_token, current_token.newlines);\n }\n\n this.print_token(current_token);\n this.set_mode(next_mode);\n if (this._options.space_in_paren) {\n this._output.space_before_token = true;\n }\n\n // In all cases, if we newline while inside an expression it should be indented.\n this.indent();\n};\n\nBeautifier.prototype.handle_end_expr = function(current_token) {\n // statements inside expressions are not valid syntax, but...\n // statements must all be closed when their container closes\n while (this._flags.mode === MODE.Statement) {\n this.restore_mode();\n }\n\n this.handle_whitespace_and_comments(current_token);\n\n if (this._flags.multiline_frame) {\n this.allow_wrap_or_preserved_newline(current_token,\n current_token.text === ']' && is_array(this._flags.mode) && !this._options.keep_array_indentation);\n }\n\n if (this._options.space_in_paren) {\n if (this._flags.last_token.type === TOKEN.START_EXPR && !this._options.space_in_empty_paren) {\n // () [] no inner space in empty parens like these, ever, ref #320\n this._output.trim();\n this._output.space_before_token = false;\n } else {\n this._output.space_before_token = true;\n }\n }\n this.deindent();\n this.print_token(current_token);\n this.restore_mode();\n\n remove_redundant_indentation(this._output, this._previous_flags);\n\n // do {} while () // no statement required after\n if (this._flags.do_while && this._previous_flags.mode === MODE.Conditional) {\n this._previous_flags.mode = MODE.Expression;\n this._flags.do_block = false;\n this._flags.do_while = false;\n\n }\n};\n\nBeautifier.prototype.handle_start_block = function(current_token) {\n this.handle_whitespace_and_comments(current_token);\n\n // Check if this is should be treated as a ObjectLiteral\n var next_token = this._tokens.peek();\n var second_token = this._tokens.peek(1);\n if (this._flags.last_word === 'switch' && this._flags.last_token.type === TOKEN.END_EXPR) {\n this.set_mode(MODE.BlockStatement);\n this._flags.in_case_statement = true;\n } else if (this._flags.case_body) {\n this.set_mode(MODE.BlockStatement);\n } else if (second_token && (\n (in_array(second_token.text, [':', ',']) && in_array(next_token.type, [TOKEN.STRING, TOKEN.WORD, TOKEN.RESERVED])) ||\n (in_array(next_token.text, ['get', 'set', '...']) && in_array(second_token.type, [TOKEN.WORD, TOKEN.RESERVED]))\n )) {\n // We don't support TypeScript,but we didn't break it for a very long time.\n // We'll try to keep not breaking it.\n if (in_array(this._last_last_text, ['class', 'interface']) && !in_array(second_token.text, [':', ','])) {\n this.set_mode(MODE.BlockStatement);\n } else {\n this.set_mode(MODE.ObjectLiteral);\n }\n } else if (this._flags.last_token.type === TOKEN.OPERATOR && this._flags.last_token.text === '=>') {\n // arrow function: (param1, paramN) => { statements }\n this.set_mode(MODE.BlockStatement);\n } else if (in_array(this._flags.last_token.type, [TOKEN.EQUALS, TOKEN.START_EXPR, TOKEN.COMMA, TOKEN.OPERATOR]) ||\n reserved_array(this._flags.last_token, ['return', 'throw', 'import', 'default'])\n ) {\n // Detecting shorthand function syntax is difficult by scanning forward,\n // so check the surrounding context.\n // If the block is being returned, imported, export default, passed as arg,\n // assigned with = or assigned in a nested object, treat as an ObjectLiteral.\n this.set_mode(MODE.ObjectLiteral);\n } else {\n this.set_mode(MODE.BlockStatement);\n }\n\n if (this._flags.last_token) {\n if (reserved_array(this._flags.last_token.previous, ['class', 'extends'])) {\n this._flags.class_start_block = true;\n }\n }\n\n var empty_braces = !next_token.comments_before && next_token.text === '}';\n var empty_anonymous_function = empty_braces && this._flags.last_word === 'function' &&\n this._flags.last_token.type === TOKEN.END_EXPR;\n\n if (this._options.brace_preserve_inline) // check for inline, set inline_frame if so\n {\n // search forward for a newline wanted inside this block\n var index = 0;\n var check_token = null;\n this._flags.inline_frame = true;\n do {\n index += 1;\n check_token = this._tokens.peek(index - 1);\n if (check_token.newlines) {\n this._flags.inline_frame = false;\n break;\n }\n } while (check_token.type !== TOKEN.EOF &&\n !(check_token.type === TOKEN.END_BLOCK && check_token.opened === current_token));\n }\n\n if ((this._options.brace_style === \"expand\" ||\n (this._options.brace_style === \"none\" && current_token.newlines)) &&\n !this._flags.inline_frame) {\n if (this._flags.last_token.type !== TOKEN.OPERATOR &&\n (empty_anonymous_function ||\n this._flags.last_token.type === TOKEN.EQUALS ||\n (reserved_array(this._flags.last_token, special_words) && this._flags.last_token.text !== 'else'))) {\n this._output.space_before_token = true;\n } else {\n this.print_newline(false, true);\n }\n } else { // collapse || inline_frame\n if (is_array(this._previous_flags.mode) && (this._flags.last_token.type === TOKEN.START_EXPR || this._flags.last_token.type === TOKEN.COMMA)) {\n if (this._flags.last_token.type === TOKEN.COMMA || this._options.space_in_paren) {\n this._output.space_before_token = true;\n }\n\n if (this._flags.last_token.type === TOKEN.COMMA || (this._flags.last_token.type === TOKEN.START_EXPR && this._flags.inline_frame)) {\n this.allow_wrap_or_preserved_newline(current_token);\n this._previous_flags.multiline_frame = this._previous_flags.multiline_frame || this._flags.multiline_frame;\n this._flags.multiline_frame = false;\n }\n }\n if (this._flags.last_token.type !== TOKEN.OPERATOR && this._flags.last_token.type !== TOKEN.START_EXPR) {\n if (this._flags.last_token.type === TOKEN.START_BLOCK && !this._flags.inline_frame) {\n this.print_newline();\n } else {\n this._output.space_before_token = true;\n }\n }\n }\n this.print_token(current_token);\n this.indent();\n\n // Except for specific cases, open braces are followed by a new line.\n if (!empty_braces && !(this._options.brace_preserve_inline && this._flags.inline_frame)) {\n this.print_newline();\n }\n};\n\nBeautifier.prototype.handle_end_block = function(current_token) {\n // statements must all be closed when their container closes\n this.handle_whitespace_and_comments(current_token);\n\n while (this._flags.mode === MODE.Statement) {\n this.restore_mode();\n }\n\n var empty_braces = this._flags.last_token.type === TOKEN.START_BLOCK;\n\n if (this._flags.inline_frame && !empty_braces) { // try inline_frame (only set if this._options.braces-preserve-inline) first\n this._output.space_before_token = true;\n } else if (this._options.brace_style === \"expand\") {\n if (!empty_braces) {\n this.print_newline();\n }\n } else {\n // skip {}\n if (!empty_braces) {\n if (is_array(this._flags.mode) && this._options.keep_array_indentation) {\n // we REALLY need a newline here, but newliner would skip that\n this._options.keep_array_indentation = false;\n this.print_newline();\n this._options.keep_array_indentation = true;\n\n } else {\n this.print_newline();\n }\n }\n }\n this.restore_mode();\n this.print_token(current_token);\n};\n\nBeautifier.prototype.handle_word = function(current_token) {\n if (current_token.type === TOKEN.RESERVED) {\n if (in_array(current_token.text, ['set', 'get']) && this._flags.mode !== MODE.ObjectLiteral) {\n current_token.type = TOKEN.WORD;\n } else if (current_token.text === 'import' && in_array(this._tokens.peek().text, ['(', '.'])) {\n current_token.type = TOKEN.WORD;\n } else if (in_array(current_token.text, ['as', 'from']) && !this._flags.import_block) {\n current_token.type = TOKEN.WORD;\n } else if (this._flags.mode === MODE.ObjectLiteral) {\n var next_token = this._tokens.peek();\n if (next_token.text === ':') {\n current_token.type = TOKEN.WORD;\n }\n }\n }\n\n if (this.start_of_statement(current_token)) {\n // The conditional starts the statement if appropriate.\n if (reserved_array(this._flags.last_token, ['var', 'let', 'const']) && current_token.type === TOKEN.WORD) {\n this._flags.declaration_statement = true;\n }\n } else if (current_token.newlines && !is_expression(this._flags.mode) &&\n (this._flags.last_token.type !== TOKEN.OPERATOR || (this._flags.last_token.text === '--' || this._flags.last_token.text === '++')) &&\n this._flags.last_token.type !== TOKEN.EQUALS &&\n (this._options.preserve_newlines || !reserved_array(this._flags.last_token, ['var', 'let', 'const', 'set', 'get']))) {\n this.handle_whitespace_and_comments(current_token);\n this.print_newline();\n } else {\n this.handle_whitespace_and_comments(current_token);\n }\n\n if (this._flags.do_block && !this._flags.do_while) {\n if (reserved_word(current_token, 'while')) {\n // do {} ## while ()\n this._output.space_before_token = true;\n this.print_token(current_token);\n this._output.space_before_token = true;\n this._flags.do_while = true;\n return;\n } else {\n // do {} should always have while as the next word.\n // if we don't see the expected while, recover\n this.print_newline();\n this._flags.do_block = false;\n }\n }\n\n // if may be followed by else, or not\n // Bare/inline ifs are tricky\n // Need to unwind the modes correctly: if (a) if (b) c(); else d(); else e();\n if (this._flags.if_block) {\n if (!this._flags.else_block && reserved_word(current_token, 'else')) {\n this._flags.else_block = true;\n } else {\n while (this._flags.mode === MODE.Statement) {\n this.restore_mode();\n }\n this._flags.if_block = false;\n this._flags.else_block = false;\n }\n }\n\n if (this._flags.in_case_statement && reserved_array(current_token, ['case', 'default'])) {\n this.print_newline();\n if (!this._flags.case_block && (this._flags.case_body || this._options.jslint_happy)) {\n // switch cases following one another\n this.deindent();\n }\n this._flags.case_body = false;\n\n this.print_token(current_token);\n this._flags.in_case = true;\n return;\n }\n\n if (this._flags.last_token.type === TOKEN.COMMA || this._flags.last_token.type === TOKEN.START_EXPR || this._flags.last_token.type === TOKEN.EQUALS || this._flags.last_token.type === TOKEN.OPERATOR) {\n if (!this.start_of_object_property()) {\n this.allow_wrap_or_preserved_newline(current_token);\n }\n }\n\n if (reserved_word(current_token, 'function')) {\n if (in_array(this._flags.last_token.text, ['}', ';']) ||\n (this._output.just_added_newline() && !(in_array(this._flags.last_token.text, ['(', '[', '{', ':', '=', ',']) || this._flags.last_token.type === TOKEN.OPERATOR))) {\n // make sure there is a nice clean space of at least one blank line\n // before a new function definition\n if (!this._output.just_added_blankline() && !current_token.comments_before) {\n this.print_newline();\n this.print_newline(true);\n }\n }\n if (this._flags.last_token.type === TOKEN.RESERVED || this._flags.last_token.type === TOKEN.WORD) {\n if (reserved_array(this._flags.last_token, ['get', 'set', 'new', 'export']) ||\n reserved_array(this._flags.last_token, newline_restricted_tokens)) {\n this._output.space_before_token = true;\n } else if (reserved_word(this._flags.last_token, 'default') && this._last_last_text === 'export') {\n this._output.space_before_token = true;\n } else if (this._flags.last_token.text === 'declare') {\n // accomodates Typescript declare function formatting\n this._output.space_before_token = true;\n } else {\n this.print_newline();\n }\n } else if (this._flags.last_token.type === TOKEN.OPERATOR || this._flags.last_token.text === '=') {\n // foo = function\n this._output.space_before_token = true;\n } else if (!this._flags.multiline_frame && (is_expression(this._flags.mode) || is_array(this._flags.mode))) {\n // (function\n } else {\n this.print_newline();\n }\n\n this.print_token(current_token);\n this._flags.last_word = current_token.text;\n return;\n }\n\n var prefix = 'NONE';\n\n if (this._flags.last_token.type === TOKEN.END_BLOCK) {\n\n if (this._previous_flags.inline_frame) {\n prefix = 'SPACE';\n } else if (!reserved_array(current_token, ['else', 'catch', 'finally', 'from'])) {\n prefix = 'NEWLINE';\n } else {\n if (this._options.brace_style === \"expand\" ||\n this._options.brace_style === \"end-expand\" ||\n (this._options.brace_style === \"none\" && current_token.newlines)) {\n prefix = 'NEWLINE';\n } else {\n prefix = 'SPACE';\n this._output.space_before_token = true;\n }\n }\n } else if (this._flags.last_token.type === TOKEN.SEMICOLON && this._flags.mode === MODE.BlockStatement) {\n // TODO: Should this be for STATEMENT as well?\n prefix = 'NEWLINE';\n } else if (this._flags.last_token.type === TOKEN.SEMICOLON && is_expression(this._flags.mode)) {\n prefix = 'SPACE';\n } else if (this._flags.last_token.type === TOKEN.STRING) {\n prefix = 'NEWLINE';\n } else if (this._flags.last_token.type === TOKEN.RESERVED || this._flags.last_token.type === TOKEN.WORD ||\n (this._flags.last_token.text === '*' &&\n (in_array(this._last_last_text, ['function', 'yield']) ||\n (this._flags.mode === MODE.ObjectLiteral && in_array(this._last_last_text, ['{', ',']))))) {\n prefix = 'SPACE';\n } else if (this._flags.last_token.type === TOKEN.START_BLOCK) {\n if (this._flags.inline_frame) {\n prefix = 'SPACE';\n } else {\n prefix = 'NEWLINE';\n }\n } else if (this._flags.last_token.type === TOKEN.END_EXPR) {\n this._output.space_before_token = true;\n prefix = 'NEWLINE';\n }\n\n if (reserved_array(current_token, line_starters) && this._flags.last_token.text !== ')') {\n if (this._flags.inline_frame || this._flags.last_token.text === 'else' || this._flags.last_token.text === 'export') {\n prefix = 'SPACE';\n } else {\n prefix = 'NEWLINE';\n }\n\n }\n\n if (reserved_array(current_token, ['else', 'catch', 'finally'])) {\n if ((!(this._flags.last_token.type === TOKEN.END_BLOCK && this._previous_flags.mode === MODE.BlockStatement) ||\n this._options.brace_style === \"expand\" ||\n this._options.brace_style === \"end-expand\" ||\n (this._options.brace_style === \"none\" && current_token.newlines)) &&\n !this._flags.inline_frame) {\n this.print_newline();\n } else {\n this._output.trim(true);\n var line = this._output.current_line;\n // If we trimmed and there's something other than a close block before us\n // put a newline back in. Handles '} // comment' scenario.\n if (line.last() !== '}') {\n this.print_newline();\n }\n this._output.space_before_token = true;\n }\n } else if (prefix === 'NEWLINE') {\n if (reserved_array(this._flags.last_token, special_words)) {\n // no newline between 'return nnn'\n this._output.space_before_token = true;\n } else if (this._flags.last_token.text === 'declare' && reserved_array(current_token, ['var', 'let', 'const'])) {\n // accomodates Typescript declare formatting\n this._output.space_before_token = true;\n } else if (this._flags.last_token.type !== TOKEN.END_EXPR) {\n if ((this._flags.last_token.type !== TOKEN.START_EXPR || !reserved_array(current_token, ['var', 'let', 'const'])) && this._flags.last_token.text !== ':') {\n // no need to force newline on 'var': for (var x = 0...)\n if (reserved_word(current_token, 'if') && reserved_word(current_token.previous, 'else')) {\n // no newline for } else if {\n this._output.space_before_token = true;\n } else {\n this.print_newline();\n }\n }\n } else if (reserved_array(current_token, line_starters) && this._flags.last_token.text !== ')') {\n this.print_newline();\n }\n } else if (this._flags.multiline_frame && is_array(this._flags.mode) && this._flags.last_token.text === ',' && this._last_last_text === '}') {\n this.print_newline(); // }, in lists get a newline treatment\n } else if (prefix === 'SPACE') {\n this._output.space_before_token = true;\n }\n if (current_token.previous && (current_token.previous.type === TOKEN.WORD || current_token.previous.type === TOKEN.RESERVED)) {\n this._output.space_before_token = true;\n }\n this.print_token(current_token);\n this._flags.last_word = current_token.text;\n\n if (current_token.type === TOKEN.RESERVED) {\n if (current_token.text === 'do') {\n this._flags.do_block = true;\n } else if (current_token.text === 'if') {\n this._flags.if_block = true;\n } else if (current_token.text === 'import') {\n this._flags.import_block = true;\n } else if (this._flags.import_block && reserved_word(current_token, 'from')) {\n this._flags.import_block = false;\n }\n }\n};\n\nBeautifier.prototype.handle_semicolon = function(current_token) {\n if (this.start_of_statement(current_token)) {\n // The conditional starts the statement if appropriate.\n // Semicolon can be the start (and end) of a statement\n this._output.space_before_token = false;\n } else {\n this.handle_whitespace_and_comments(current_token);\n }\n\n var next_token = this._tokens.peek();\n while (this._flags.mode === MODE.Statement &&\n !(this._flags.if_block && reserved_word(next_token, 'else')) &&\n !this._flags.do_block) {\n this.restore_mode();\n }\n\n // hacky but effective for the moment\n if (this._flags.import_block) {\n this._flags.import_block = false;\n }\n this.print_token(current_token);\n};\n\nBeautifier.prototype.handle_string = function(current_token) {\n if (current_token.text.startsWith(\"`\") && current_token.newlines === 0 && current_token.whitespace_before === '' && (current_token.previous.text === ')' || this._flags.last_token.type === TOKEN.WORD)) {\n //Conditional for detectign backtick strings\n } else if (this.start_of_statement(current_token)) {\n // The conditional starts the statement if appropriate.\n // One difference - strings want at least a space before\n this._output.space_before_token = true;\n } else {\n this.handle_whitespace_and_comments(current_token);\n if (this._flags.last_token.type === TOKEN.RESERVED || this._flags.last_token.type === TOKEN.WORD || this._flags.inline_frame) {\n this._output.space_before_token = true;\n } else if (this._flags.last_token.type === TOKEN.COMMA || this._flags.last_token.type === TOKEN.START_EXPR || this._flags.last_token.type === TOKEN.EQUALS || this._flags.last_token.type === TOKEN.OPERATOR) {\n if (!this.start_of_object_property()) {\n this.allow_wrap_or_preserved_newline(current_token);\n }\n } else if ((current_token.text.startsWith(\"`\") && this._flags.last_token.type === TOKEN.END_EXPR && (current_token.previous.text === ']' || current_token.previous.text === ')') && current_token.newlines === 0)) {\n this._output.space_before_token = true;\n } else {\n this.print_newline();\n }\n }\n this.print_token(current_token);\n};\n\nBeautifier.prototype.handle_equals = function(current_token) {\n if (this.start_of_statement(current_token)) {\n // The conditional starts the statement if appropriate.\n } else {\n this.handle_whitespace_and_comments(current_token);\n }\n\n if (this._flags.declaration_statement) {\n // just got an '=' in a var-line, different formatting/line-breaking, etc will now be done\n this._flags.declaration_assignment = true;\n }\n this._output.space_before_token = true;\n this.print_token(current_token);\n this._output.space_before_token = true;\n};\n\nBeautifier.prototype.handle_comma = function(current_token) {\n this.handle_whitespace_and_comments(current_token, true);\n\n this.print_token(current_token);\n this._output.space_before_token = true;\n if (this._flags.declaration_statement) {\n if (is_expression(this._flags.parent.mode)) {\n // do not break on comma, for(var a = 1, b = 2)\n this._flags.declaration_assignment = false;\n }\n\n if (this._flags.declaration_assignment) {\n this._flags.declaration_assignment = false;\n this.print_newline(false, true);\n } else if (this._options.comma_first) {\n // for comma-first, we want to allow a newline before the comma\n // to turn into a newline after the comma, which we will fixup later\n this.allow_wrap_or_preserved_newline(current_token);\n }\n } else if (this._flags.mode === MODE.ObjectLiteral ||\n (this._flags.mode === MODE.Statement && this._flags.parent.mode === MODE.ObjectLiteral)) {\n if (this._flags.mode === MODE.Statement) {\n this.restore_mode();\n }\n\n if (!this._flags.inline_frame) {\n this.print_newline();\n }\n } else if (this._options.comma_first) {\n // EXPR or DO_BLOCK\n // for comma-first, we want to allow a newline before the comma\n // to turn into a newline after the comma, which we will fixup later\n this.allow_wrap_or_preserved_newline(current_token);\n }\n};\n\nBeautifier.prototype.handle_operator = function(current_token) {\n var isGeneratorAsterisk = current_token.text === '*' &&\n (reserved_array(this._flags.last_token, ['function', 'yield']) ||\n (in_array(this._flags.last_token.type, [TOKEN.START_BLOCK, TOKEN.COMMA, TOKEN.END_BLOCK, TOKEN.SEMICOLON]))\n );\n var isUnary = in_array(current_token.text, ['-', '+']) && (\n in_array(this._flags.last_token.type, [TOKEN.START_BLOCK, TOKEN.START_EXPR, TOKEN.EQUALS, TOKEN.OPERATOR]) ||\n in_array(this._flags.last_token.text, line_starters) ||\n this._flags.last_token.text === ','\n );\n\n if (this.start_of_statement(current_token)) {\n // The conditional starts the statement if appropriate.\n } else {\n var preserve_statement_flags = !isGeneratorAsterisk;\n this.handle_whitespace_and_comments(current_token, preserve_statement_flags);\n }\n\n // hack for actionscript's import .*;\n if (current_token.text === '*' && this._flags.last_token.type === TOKEN.DOT) {\n this.print_token(current_token);\n return;\n }\n\n if (current_token.text === '::') {\n // no spaces around exotic namespacing syntax operator\n this.print_token(current_token);\n return;\n }\n\n // Allow line wrapping between operators when operator_position is\n // set to before or preserve\n if (this._flags.last_token.type === TOKEN.OPERATOR && in_array(this._options.operator_position, OPERATOR_POSITION_BEFORE_OR_PRESERVE)) {\n this.allow_wrap_or_preserved_newline(current_token);\n }\n\n if (current_token.text === ':' && this._flags.in_case) {\n this.print_token(current_token);\n\n this._flags.in_case = false;\n this._flags.case_body = true;\n if (this._tokens.peek().type !== TOKEN.START_BLOCK) {\n this.indent();\n this.print_newline();\n this._flags.case_block = false;\n } else {\n this._flags.case_block = true;\n this._output.space_before_token = true;\n }\n return;\n }\n\n var space_before = true;\n var space_after = true;\n var in_ternary = false;\n if (current_token.text === ':') {\n if (this._flags.ternary_depth === 0) {\n // Colon is invalid javascript outside of ternary and object, but do our best to guess what was meant.\n space_before = false;\n } else {\n this._flags.ternary_depth -= 1;\n in_ternary = true;\n }\n } else if (current_token.text === '?') {\n this._flags.ternary_depth += 1;\n }\n\n // let's handle the operator_position option prior to any conflicting logic\n if (!isUnary && !isGeneratorAsterisk && this._options.preserve_newlines && in_array(current_token.text, positionable_operators)) {\n var isColon = current_token.text === ':';\n var isTernaryColon = (isColon && in_ternary);\n var isOtherColon = (isColon && !in_ternary);\n\n switch (this._options.operator_position) {\n case OPERATOR_POSITION.before_newline:\n // if the current token is : and it's not a ternary statement then we set space_before to false\n this._output.space_before_token = !isOtherColon;\n\n this.print_token(current_token);\n\n if (!isColon || isTernaryColon) {\n this.allow_wrap_or_preserved_newline(current_token);\n }\n\n this._output.space_before_token = true;\n return;\n\n case OPERATOR_POSITION.after_newline:\n // if the current token is anything but colon, or (via deduction) it's a colon and in a ternary statement,\n // then print a newline.\n\n this._output.space_before_token = true;\n\n if (!isColon || isTernaryColon) {\n if (this._tokens.peek().newlines) {\n this.print_newline(false, true);\n } else {\n this.allow_wrap_or_preserved_newline(current_token);\n }\n } else {\n this._output.space_before_token = false;\n }\n\n this.print_token(current_token);\n\n this._output.space_before_token = true;\n return;\n\n case OPERATOR_POSITION.preserve_newline:\n if (!isOtherColon) {\n this.allow_wrap_or_preserved_newline(current_token);\n }\n\n // if we just added a newline, or the current token is : and it's not a ternary statement,\n // then we set space_before to false\n space_before = !(this._output.just_added_newline() || isOtherColon);\n\n this._output.space_before_token = space_before;\n this.print_token(current_token);\n this._output.space_before_token = true;\n return;\n }\n }\n\n if (isGeneratorAsterisk) {\n this.allow_wrap_or_preserved_newline(current_token);\n space_before = false;\n var next_token = this._tokens.peek();\n space_after = next_token && in_array(next_token.type, [TOKEN.WORD, TOKEN.RESERVED]);\n } else if (current_token.text === '...') {\n this.allow_wrap_or_preserved_newline(current_token);\n space_before = this._flags.last_token.type === TOKEN.START_BLOCK;\n space_after = false;\n } else if (in_array(current_token.text, ['--', '++', '!', '~']) || isUnary) {\n // unary operators (and binary +/- pretending to be unary) special cases\n if (this._flags.last_token.type === TOKEN.COMMA || this._flags.last_token.type === TOKEN.START_EXPR) {\n this.allow_wrap_or_preserved_newline(current_token);\n }\n\n space_before = false;\n space_after = false;\n\n // http://www.ecma-international.org/ecma-262/5.1/#sec-7.9.1\n // if there is a newline between -- or ++ and anything else we should preserve it.\n if (current_token.newlines && (current_token.text === '--' || current_token.text === '++' || current_token.text === '~')) {\n var new_line_needed = reserved_array(this._flags.last_token, special_words) && current_token.newlines;\n if (new_line_needed && (this._previous_flags.if_block || this._previous_flags.else_block)) {\n this.restore_mode();\n }\n this.print_newline(new_line_needed, true);\n }\n\n if (this._flags.last_token.text === ';' && is_expression(this._flags.mode)) {\n // for (;; ++i)\n // ^^^\n space_before = true;\n }\n\n if (this._flags.last_token.type === TOKEN.RESERVED) {\n space_before = true;\n } else if (this._flags.last_token.type === TOKEN.END_EXPR) {\n space_before = !(this._flags.last_token.text === ']' && (current_token.text === '--' || current_token.text === '++'));\n } else if (this._flags.last_token.type === TOKEN.OPERATOR) {\n // a++ + ++b;\n // a - -b\n space_before = in_array(current_token.text, ['--', '-', '++', '+']) && in_array(this._flags.last_token.text, ['--', '-', '++', '+']);\n // + and - are not unary when preceeded by -- or ++ operator\n // a-- + b\n // a * +b\n // a - -b\n if (in_array(current_token.text, ['+', '-']) && in_array(this._flags.last_token.text, ['--', '++'])) {\n space_after = true;\n }\n }\n\n\n if (((this._flags.mode === MODE.BlockStatement && !this._flags.inline_frame) || this._flags.mode === MODE.Statement) &&\n (this._flags.last_token.text === '{' || this._flags.last_token.text === ';')) {\n // { foo; --i }\n // foo(); --bar;\n this.print_newline();\n }\n }\n\n this._output.space_before_token = this._output.space_before_token || space_before;\n this.print_token(current_token);\n this._output.space_before_token = space_after;\n};\n\nBeautifier.prototype.handle_block_comment = function(current_token, preserve_statement_flags) {\n if (this._output.raw) {\n this._output.add_raw_token(current_token);\n if (current_token.directives && current_token.directives.preserve === 'end') {\n // If we're testing the raw output behavior, do not allow a directive to turn it off.\n this._output.raw = this._options.test_output_raw;\n }\n return;\n }\n\n if (current_token.directives) {\n this.print_newline(false, preserve_statement_flags);\n this.print_token(current_token);\n if (current_token.directives.preserve === 'start') {\n this._output.raw = true;\n }\n this.print_newline(false, true);\n return;\n }\n\n // inline block\n if (!acorn.newline.test(current_token.text) && !current_token.newlines) {\n this._output.space_before_token = true;\n this.print_token(current_token);\n this._output.space_before_token = true;\n return;\n } else {\n this.print_block_commment(current_token, preserve_statement_flags);\n }\n};\n\nBeautifier.prototype.print_block_commment = function(current_token, preserve_statement_flags) {\n var lines = split_linebreaks(current_token.text);\n var j; // iterator for this case\n var javadoc = false;\n var starless = false;\n var lastIndent = current_token.whitespace_before;\n var lastIndentLength = lastIndent.length;\n\n // block comment starts with a new line\n this.print_newline(false, preserve_statement_flags);\n\n // first line always indented\n this.print_token_line_indentation(current_token);\n this._output.add_token(lines[0]);\n this.print_newline(false, preserve_statement_flags);\n\n\n if (lines.length > 1) {\n lines = lines.slice(1);\n javadoc = all_lines_start_with(lines, '*');\n starless = each_line_matches_indent(lines, lastIndent);\n\n if (javadoc) {\n this._flags.alignment = 1;\n }\n\n for (j = 0; j < lines.length; j++) {\n if (javadoc) {\n // javadoc: reformat and re-indent\n this.print_token_line_indentation(current_token);\n this._output.add_token(ltrim(lines[j]));\n } else if (starless && lines[j]) {\n // starless: re-indent non-empty content, avoiding trim\n this.print_token_line_indentation(current_token);\n this._output.add_token(lines[j].substring(lastIndentLength));\n } else {\n // normal comments output raw\n this._output.current_line.set_indent(-1);\n this._output.add_token(lines[j]);\n }\n\n // for comments on their own line or more than one line, make sure there's a new line after\n this.print_newline(false, preserve_statement_flags);\n }\n\n this._flags.alignment = 0;\n }\n};\n\n\nBeautifier.prototype.handle_comment = function(current_token, preserve_statement_flags) {\n if (current_token.newlines) {\n this.print_newline(false, preserve_statement_flags);\n } else {\n this._output.trim(true);\n }\n\n this._output.space_before_token = true;\n this.print_token(current_token);\n this.print_newline(false, preserve_statement_flags);\n};\n\nBeautifier.prototype.handle_dot = function(current_token) {\n if (this.start_of_statement(current_token)) {\n // The conditional starts the statement if appropriate.\n } else {\n this.handle_whitespace_and_comments(current_token, true);\n }\n\n if (this._flags.last_token.text.match('^[0-9]+$')) {\n this._output.space_before_token = true;\n }\n\n if (reserved_array(this._flags.last_token, special_words)) {\n this._output.space_before_token = false;\n } else {\n // allow preserved newlines before dots in general\n // force newlines on dots after close paren when break_chained - for bar().baz()\n this.allow_wrap_or_preserved_newline(current_token,\n this._flags.last_token.text === ')' && this._options.break_chained_methods);\n }\n\n // Only unindent chained method dot if this dot starts a new line.\n // Otherwise the automatic extra indentation removal will handle the over indent\n if (this._options.unindent_chained_methods && this._output.just_added_newline()) {\n this.deindent();\n }\n\n this.print_token(current_token);\n};\n\nBeautifier.prototype.handle_unknown = function(current_token, preserve_statement_flags) {\n this.print_token(current_token);\n\n if (current_token.text[current_token.text.length - 1] === '\\n') {\n this.print_newline(false, preserve_statement_flags);\n }\n};\n\nBeautifier.prototype.handle_eof = function(current_token) {\n // Unwind any open statements\n while (this._flags.mode === MODE.Statement) {\n this.restore_mode();\n }\n this.handle_whitespace_and_comments(current_token);\n};\n\nmodule.exports.Beautifier = Beautifier;\n","/*jshint node:true */\n/*\n\n The MIT License (MIT)\n\n Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.\n\n Permission is hereby granted, free of charge, to any person\n obtaining a copy of this software and associated documentation files\n (the \"Software\"), to deal in the Software without restriction,\n including without limitation the rights to use, copy, modify, merge,\n publish, distribute, sublicense, and/or sell copies of the Software,\n and to permit persons to whom the Software is furnished to do so,\n subject to the following conditions:\n\n The above copyright notice and this permission notice shall be\n included in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n*/\n\n'use strict';\n\nvar Beautifier = require('./beautifier').Beautifier,\n Options = require('./options').Options;\n\nfunction js_beautify(js_source_text, options) {\n var beautifier = new Beautifier(js_source_text, options);\n return beautifier.beautify();\n}\n\nmodule.exports = js_beautify;\nmodule.exports.defaultOptions = function() {\n return new Options();\n};\n","/*jshint node:true */\n/*\n\n The MIT License (MIT)\n\n Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.\n\n Permission is hereby granted, free of charge, to any person\n obtaining a copy of this software and associated documentation files\n (the \"Software\"), to deal in the Software without restriction,\n including without limitation the rights to use, copy, modify, merge,\n publish, distribute, sublicense, and/or sell copies of the Software,\n and to permit persons to whom the Software is furnished to do so,\n subject to the following conditions:\n\n The above copyright notice and this permission notice shall be\n included in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n*/\n\n'use strict';\n\nvar BaseOptions = require('../core/options').Options;\n\nfunction Options(options) {\n BaseOptions.call(this, options, 'css');\n\n this.selector_separator_newline = this._get_boolean('selector_separator_newline', true);\n this.newline_between_rules = this._get_boolean('newline_between_rules', true);\n var space_around_selector_separator = this._get_boolean('space_around_selector_separator');\n this.space_around_combinator = this._get_boolean('space_around_combinator') || space_around_selector_separator;\n\n var brace_style_split = this._get_selection_list('brace_style', ['collapse', 'expand', 'end-expand', 'none', 'preserve-inline']);\n this.brace_style = 'collapse';\n for (var bs = 0; bs < brace_style_split.length; bs++) {\n if (brace_style_split[bs] !== 'expand') {\n // default to collapse, as only collapse|expand is implemented for now\n this.brace_style = 'collapse';\n } else {\n this.brace_style = brace_style_split[bs];\n }\n }\n}\nOptions.prototype = new BaseOptions();\n\n\n\nmodule.exports.Options = Options;\n","/*jshint node:true */\n/*\n\n The MIT License (MIT)\n\n Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.\n\n Permission is hereby granted, free of charge, to any person\n obtaining a copy of this software and associated documentation files\n (the \"Software\"), to deal in the Software without restriction,\n including without limitation the rights to use, copy, modify, merge,\n publish, distribute, sublicense, and/or sell copies of the Software,\n and to permit persons to whom the Software is furnished to do so,\n subject to the following conditions:\n\n The above copyright notice and this permission notice shall be\n included in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n*/\n\n'use strict';\n\nvar Options = require('./options').Options;\nvar Output = require('../core/output').Output;\nvar InputScanner = require('../core/inputscanner').InputScanner;\nvar Directives = require('../core/directives').Directives;\n\nvar directives_core = new Directives(/\\/\\*/, /\\*\\//);\n\nvar lineBreak = /\\r\\n|[\\r\\n]/;\nvar allLineBreaks = /\\r\\n|[\\r\\n]/g;\n\n// tokenizer\nvar whitespaceChar = /\\s/;\nvar whitespacePattern = /(?:\\s|\\n)+/g;\nvar block_comment_pattern = /\\/\\*(?:[\\s\\S]*?)((?:\\*\\/)|$)/g;\nvar comment_pattern = /\\/\\/(?:[^\\n\\r\\u2028\\u2029]*)/g;\n\nfunction Beautifier(source_text, options) {\n this._source_text = source_text || '';\n // Allow the setting of language/file-type specific options\n // with inheritance of overall settings\n this._options = new Options(options);\n this._ch = null;\n this._input = null;\n\n // https://developer.mozilla.org/en-US/docs/Web/CSS/At-rule\n this.NESTED_AT_RULE = {\n \"@page\": true,\n \"@font-face\": true,\n \"@keyframes\": true,\n // also in CONDITIONAL_GROUP_RULE below\n \"@media\": true,\n \"@supports\": true,\n \"@document\": true\n };\n this.CONDITIONAL_GROUP_RULE = {\n \"@media\": true,\n \"@supports\": true,\n \"@document\": true\n };\n this.NON_SEMICOLON_NEWLINE_PROPERTY = [\n \"grid-template-areas\",\n \"grid-template\"\n ];\n\n}\n\nBeautifier.prototype.eatString = function(endChars) {\n var result = '';\n this._ch = this._input.next();\n while (this._ch) {\n result += this._ch;\n if (this._ch === \"\\\\\") {\n result += this._input.next();\n } else if (endChars.indexOf(this._ch) !== -1 || this._ch === \"\\n\") {\n break;\n }\n this._ch = this._input.next();\n }\n return result;\n};\n\n// Skips any white space in the source text from the current position.\n// When allowAtLeastOneNewLine is true, will output new lines for each\n// newline character found; if the user has preserve_newlines off, only\n// the first newline will be output\nBeautifier.prototype.eatWhitespace = function(allowAtLeastOneNewLine) {\n var result = whitespaceChar.test(this._input.peek());\n var newline_count = 0;\n while (whitespaceChar.test(this._input.peek())) {\n this._ch = this._input.next();\n if (allowAtLeastOneNewLine && this._ch === '\\n') {\n if (newline_count === 0 || newline_count < this._options.max_preserve_newlines) {\n newline_count++;\n this._output.add_new_line(true);\n }\n }\n }\n return result;\n};\n\n// Nested pseudo-class if we are insideRule\n// and the next special character found opens\n// a new block\nBeautifier.prototype.foundNestedPseudoClass = function() {\n var openParen = 0;\n var i = 1;\n var ch = this._input.peek(i);\n while (ch) {\n if (ch === \"{\") {\n return true;\n } else if (ch === '(') {\n // pseudoclasses can contain ()\n openParen += 1;\n } else if (ch === ')') {\n if (openParen === 0) {\n return false;\n }\n openParen -= 1;\n } else if (ch === \";\" || ch === \"}\") {\n return false;\n }\n i++;\n ch = this._input.peek(i);\n }\n return false;\n};\n\nBeautifier.prototype.print_string = function(output_string) {\n this._output.set_indent(this._indentLevel);\n this._output.non_breaking_space = true;\n this._output.add_token(output_string);\n};\n\nBeautifier.prototype.preserveSingleSpace = function(isAfterSpace) {\n if (isAfterSpace) {\n this._output.space_before_token = true;\n }\n};\n\nBeautifier.prototype.indent = function() {\n this._indentLevel++;\n};\n\nBeautifier.prototype.outdent = function() {\n if (this._indentLevel > 0) {\n this._indentLevel--;\n }\n};\n\n/*_____________________--------------------_____________________*/\n\nBeautifier.prototype.beautify = function() {\n if (this._options.disabled) {\n return this._source_text;\n }\n\n var source_text = this._source_text;\n var eol = this._options.eol;\n if (eol === 'auto') {\n eol = '\\n';\n if (source_text && lineBreak.test(source_text || '')) {\n eol = source_text.match(lineBreak)[0];\n }\n }\n\n\n // HACK: newline parsing inconsistent. This brute force normalizes the this._input.\n source_text = source_text.replace(allLineBreaks, '\\n');\n\n // reset\n var baseIndentString = source_text.match(/^[\\t ]*/)[0];\n\n this._output = new Output(this._options, baseIndentString);\n this._input = new InputScanner(source_text);\n this._indentLevel = 0;\n this._nestedLevel = 0;\n\n this._ch = null;\n var parenLevel = 0;\n\n var insideRule = false;\n // This is the value side of a property value pair (blue in the following ex)\n // label { content: blue }\n var insidePropertyValue = false;\n var enteringConditionalGroup = false;\n var insideAtExtend = false;\n var insideAtImport = false;\n var insideScssMap = false;\n var topCharacter = this._ch;\n var insideNonSemiColonValues = false;\n var whitespace;\n var isAfterSpace;\n var previous_ch;\n\n while (true) {\n whitespace = this._input.read(whitespacePattern);\n isAfterSpace = whitespace !== '';\n previous_ch = topCharacter;\n this._ch = this._input.next();\n if (this._ch === '\\\\' && this._input.hasNext()) {\n this._ch += this._input.next();\n }\n topCharacter = this._ch;\n\n if (!this._ch) {\n break;\n } else if (this._ch === '/' && this._input.peek() === '*') {\n // /* css comment */\n // Always start block comments on a new line.\n // This handles scenarios where a block comment immediately\n // follows a property definition on the same line or where\n // minified code is being beautified.\n this._output.add_new_line();\n this._input.back();\n\n var comment = this._input.read(block_comment_pattern);\n\n // Handle ignore directive\n var directives = directives_core.get_directives(comment);\n if (directives && directives.ignore === 'start') {\n comment += directives_core.readIgnored(this._input);\n }\n\n this.print_string(comment);\n\n // Ensures any new lines following the comment are preserved\n this.eatWhitespace(true);\n\n // Block comments are followed by a new line so they don't\n // share a line with other properties\n this._output.add_new_line();\n } else if (this._ch === '/' && this._input.peek() === '/') {\n // // single line comment\n // Preserves the space before a comment\n // on the same line as a rule\n this._output.space_before_token = true;\n this._input.back();\n this.print_string(this._input.read(comment_pattern));\n\n // Ensures any new lines following the comment are preserved\n this.eatWhitespace(true);\n } else if (this._ch === '@' || this._ch === '$') {\n this.preserveSingleSpace(isAfterSpace);\n\n // deal with less propery mixins @{...}\n if (this._input.peek() === '{') {\n this.print_string(this._ch + this.eatString('}'));\n } else {\n this.print_string(this._ch);\n\n // strip trailing space, if present, for hash property checks\n var variableOrRule = this._input.peekUntilAfter(/[: ,;{}()[\\]\\/='\"]/g);\n\n if (variableOrRule.match(/[ :]$/)) {\n // we have a variable or pseudo-class, add it and insert one space before continuing\n variableOrRule = this.eatString(\": \").replace(/\\s$/, '');\n this.print_string(variableOrRule);\n this._output.space_before_token = true;\n }\n\n variableOrRule = variableOrRule.replace(/\\s$/, '');\n\n if (variableOrRule === 'extend') {\n insideAtExtend = true;\n } else if (variableOrRule === 'import') {\n insideAtImport = true;\n }\n\n // might be a nesting at-rule\n if (variableOrRule in this.NESTED_AT_RULE) {\n this._nestedLevel += 1;\n if (variableOrRule in this.CONDITIONAL_GROUP_RULE) {\n enteringConditionalGroup = true;\n }\n // might be less variable\n } else if (!insideRule && parenLevel === 0 && variableOrRule.indexOf(':') !== -1) {\n insidePropertyValue = true;\n this.indent();\n }\n }\n } else if (this._ch === '#' && this._input.peek() === '{') {\n this.preserveSingleSpace(isAfterSpace);\n this.print_string(this._ch + this.eatString('}'));\n } else if (this._ch === '{') {\n if (insidePropertyValue) {\n insidePropertyValue = false;\n this.outdent();\n }\n\n // when entering conditional groups, only rulesets are allowed\n if (enteringConditionalGroup) {\n enteringConditionalGroup = false;\n insideRule = (this._indentLevel >= this._nestedLevel);\n } else {\n // otherwise, declarations are also allowed\n insideRule = (this._indentLevel >= this._nestedLevel - 1);\n }\n if (this._options.newline_between_rules && insideRule) {\n if (this._output.previous_line && this._output.previous_line.item(-1) !== '{') {\n this._output.ensure_empty_line_above('/', ',');\n }\n }\n\n this._output.space_before_token = true;\n\n // The difference in print_string and indent order is necessary to indent the '{' correctly\n if (this._options.brace_style === 'expand') {\n this._output.add_new_line();\n this.print_string(this._ch);\n this.indent();\n this._output.set_indent(this._indentLevel);\n } else {\n // inside mixin and first param is object\n if (previous_ch === '(') {\n this._output.space_before_token = false;\n } else if (previous_ch !== ',') {\n this.indent();\n }\n this.print_string(this._ch);\n }\n\n this.eatWhitespace(true);\n this._output.add_new_line();\n } else if (this._ch === '}') {\n this.outdent();\n this._output.add_new_line();\n if (previous_ch === '{') {\n this._output.trim(true);\n }\n insideAtImport = false;\n insideAtExtend = false;\n if (insidePropertyValue) {\n this.outdent();\n insidePropertyValue = false;\n }\n this.print_string(this._ch);\n insideRule = false;\n if (this._nestedLevel) {\n this._nestedLevel--;\n }\n\n this.eatWhitespace(true);\n this._output.add_new_line();\n\n if (this._options.newline_between_rules && !this._output.just_added_blankline()) {\n if (this._input.peek() !== '}') {\n this._output.add_new_line(true);\n }\n }\n if (this._input.peek() === ')') {\n this._output.trim(true);\n if (this._options.brace_style === \"expand\") {\n this._output.add_new_line(true);\n }\n }\n } else if (this._ch === \":\") {\n\n for (var i = 0; i < this.NON_SEMICOLON_NEWLINE_PROPERTY.length; i++) {\n if (this._input.lookBack(this.NON_SEMICOLON_NEWLINE_PROPERTY[i])) {\n insideNonSemiColonValues = true;\n break;\n }\n }\n\n if ((insideRule || enteringConditionalGroup) && !(this._input.lookBack(\"&\") || this.foundNestedPseudoClass()) && !this._input.lookBack(\"(\") && !insideAtExtend && parenLevel === 0) {\n // 'property: value' delimiter\n // which could be in a conditional group query\n this.print_string(':');\n if (!insidePropertyValue) {\n insidePropertyValue = true;\n this._output.space_before_token = true;\n this.eatWhitespace(true);\n this.indent();\n }\n } else {\n // sass/less parent reference don't use a space\n // sass nested pseudo-class don't use a space\n\n // preserve space before pseudoclasses/pseudoelements, as it means \"in any child\"\n if (this._input.lookBack(\" \")) {\n this._output.space_before_token = true;\n }\n if (this._input.peek() === \":\") {\n // pseudo-element\n this._ch = this._input.next();\n this.print_string(\"::\");\n } else {\n // pseudo-class\n this.print_string(':');\n }\n }\n } else if (this._ch === '\"' || this._ch === '\\'') {\n var preserveQuoteSpace = previous_ch === '\"' || previous_ch === '\\'';\n this.preserveSingleSpace(preserveQuoteSpace || isAfterSpace);\n this.print_string(this._ch + this.eatString(this._ch));\n this.eatWhitespace(true);\n } else if (this._ch === ';') {\n insideNonSemiColonValues = false;\n if (parenLevel === 0) {\n if (insidePropertyValue) {\n this.outdent();\n insidePropertyValue = false;\n }\n insideAtExtend = false;\n insideAtImport = false;\n this.print_string(this._ch);\n this.eatWhitespace(true);\n\n // This maintains single line comments on the same\n // line. Block comments are also affected, but\n // a new line is always output before one inside\n // that section\n if (this._input.peek() !== '/') {\n this._output.add_new_line();\n }\n } else {\n this.print_string(this._ch);\n this.eatWhitespace(true);\n this._output.space_before_token = true;\n }\n } else if (this._ch === '(') { // may be a url\n if (this._input.lookBack(\"url\")) {\n this.print_string(this._ch);\n this.eatWhitespace();\n parenLevel++;\n this.indent();\n this._ch = this._input.next();\n if (this._ch === ')' || this._ch === '\"' || this._ch === '\\'') {\n this._input.back();\n } else if (this._ch) {\n this.print_string(this._ch + this.eatString(')'));\n if (parenLevel) {\n parenLevel--;\n this.outdent();\n }\n }\n } else {\n var space_needed = false;\n if (this._input.lookBack(\"with\")) {\n // look back is not an accurate solution, we need tokens to confirm without whitespaces\n space_needed = true;\n }\n this.preserveSingleSpace(isAfterSpace || space_needed);\n this.print_string(this._ch);\n\n // handle scss/sass map\n if (insidePropertyValue && previous_ch === \"$\" && this._options.selector_separator_newline) {\n this._output.add_new_line();\n insideScssMap = true;\n } else {\n this.eatWhitespace();\n parenLevel++;\n this.indent();\n }\n }\n } else if (this._ch === ')') {\n if (parenLevel) {\n parenLevel--;\n this.outdent();\n }\n if (insideScssMap && this._input.peek() === \";\" && this._options.selector_separator_newline) {\n insideScssMap = false;\n this.outdent();\n this._output.add_new_line();\n }\n this.print_string(this._ch);\n } else if (this._ch === ',') {\n this.print_string(this._ch);\n this.eatWhitespace(true);\n if (this._options.selector_separator_newline && (!insidePropertyValue || insideScssMap) && parenLevel === 0 && !insideAtImport && !insideAtExtend) {\n this._output.add_new_line();\n } else {\n this._output.space_before_token = true;\n }\n } else if ((this._ch === '>' || this._ch === '+' || this._ch === '~') && !insidePropertyValue && parenLevel === 0) {\n //handle combinator spacing\n if (this._options.space_around_combinator) {\n this._output.space_before_token = true;\n this.print_string(this._ch);\n this._output.space_before_token = true;\n } else {\n this.print_string(this._ch);\n this.eatWhitespace();\n // squash extra whitespace\n if (this._ch && whitespaceChar.test(this._ch)) {\n this._ch = '';\n }\n }\n } else if (this._ch === ']') {\n this.print_string(this._ch);\n } else if (this._ch === '[') {\n this.preserveSingleSpace(isAfterSpace);\n this.print_string(this._ch);\n } else if (this._ch === '=') { // no whitespace before or after\n this.eatWhitespace();\n this.print_string('=');\n if (whitespaceChar.test(this._ch)) {\n this._ch = '';\n }\n } else if (this._ch === '!' && !this._input.lookBack(\"\\\\\")) { // !important\n this._output.space_before_token = true;\n this.print_string(this._ch);\n } else {\n var preserveAfterSpace = previous_ch === '\"' || previous_ch === '\\'';\n this.preserveSingleSpace(preserveAfterSpace || isAfterSpace);\n this.print_string(this._ch);\n\n if (!this._output.just_added_newline() && this._input.peek() === '\\n' && insideNonSemiColonValues) {\n this._output.add_new_line();\n }\n }\n }\n\n var sweetCode = this._output.get_code(eol);\n\n return sweetCode;\n};\n\nmodule.exports.Beautifier = Beautifier;\n","/*jshint node:true */\n/*\n\n The MIT License (MIT)\n\n Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.\n\n Permission is hereby granted, free of charge, to any person\n obtaining a copy of this software and associated documentation files\n (the \"Software\"), to deal in the Software without restriction,\n including without limitation the rights to use, copy, modify, merge,\n publish, distribute, sublicense, and/or sell copies of the Software,\n and to permit persons to whom the Software is furnished to do so,\n subject to the following conditions:\n\n The above copyright notice and this permission notice shall be\n included in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n*/\n\n'use strict';\n\nvar Beautifier = require('./beautifier').Beautifier,\n Options = require('./options').Options;\n\nfunction css_beautify(source_text, options) {\n var beautifier = new Beautifier(source_text, options);\n return beautifier.beautify();\n}\n\nmodule.exports = css_beautify;\nmodule.exports.defaultOptions = function() {\n return new Options();\n};\n","/*jshint node:true */\n/*\n\n The MIT License (MIT)\n\n Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.\n\n Permission is hereby granted, free of charge, to any person\n obtaining a copy of this software and associated documentation files\n (the \"Software\"), to deal in the Software without restriction,\n including without limitation the rights to use, copy, modify, merge,\n publish, distribute, sublicense, and/or sell copies of the Software,\n and to permit persons to whom the Software is furnished to do so,\n subject to the following conditions:\n\n The above copyright notice and this permission notice shall be\n included in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n*/\n\n'use strict';\n\nvar BaseOptions = require('../core/options').Options;\n\nfunction Options(options) {\n BaseOptions.call(this, options, 'html');\n if (this.templating.length === 1 && this.templating[0] === 'auto') {\n this.templating = ['django', 'erb', 'handlebars', 'php'];\n }\n\n this.indent_inner_html = this._get_boolean('indent_inner_html');\n this.indent_body_inner_html = this._get_boolean('indent_body_inner_html', true);\n this.indent_head_inner_html = this._get_boolean('indent_head_inner_html', true);\n\n this.indent_handlebars = this._get_boolean('indent_handlebars', true);\n this.wrap_attributes = this._get_selection('wrap_attributes',\n ['auto', 'force', 'force-aligned', 'force-expand-multiline', 'aligned-multiple', 'preserve', 'preserve-aligned']);\n this.wrap_attributes_indent_size = this._get_number('wrap_attributes_indent_size', this.indent_size);\n this.extra_liners = this._get_array('extra_liners', ['head', 'body', '/html']);\n\n // Block vs inline elements\n // https://developer.mozilla.org/en-US/docs/Web/HTML/Block-level_elements\n // https://developer.mozilla.org/en-US/docs/Web/HTML/Inline_elements\n // https://www.w3.org/TR/html5/dom.html#phrasing-content\n this.inline = this._get_array('inline', [\n 'a', 'abbr', 'area', 'audio', 'b', 'bdi', 'bdo', 'br', 'button', 'canvas', 'cite',\n 'code', 'data', 'datalist', 'del', 'dfn', 'em', 'embed', 'i', 'iframe', 'img',\n 'input', 'ins', 'kbd', 'keygen', 'label', 'map', 'mark', 'math', 'meter', 'noscript',\n 'object', 'output', 'progress', 'q', 'ruby', 's', 'samp', /* 'script', */ 'select', 'small',\n 'span', 'strong', 'sub', 'sup', 'svg', 'template', 'textarea', 'time', 'u', 'var',\n 'video', 'wbr', 'text',\n // obsolete inline tags\n 'acronym', 'big', 'strike', 'tt'\n ]);\n this.void_elements = this._get_array('void_elements', [\n // HTLM void elements - aka self-closing tags - aka singletons\n // https://www.w3.org/html/wg/drafts/html/master/syntax.html#void-elements\n 'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'keygen',\n 'link', 'menuitem', 'meta', 'param', 'source', 'track', 'wbr',\n // NOTE: Optional tags are too complex for a simple list\n // they are hard coded in _do_optional_end_element\n\n // Doctype and xml elements\n '!doctype', '?xml',\n\n // obsolete tags\n // basefont: https://www.computerhope.com/jargon/h/html-basefont-tag.htm\n // isndex: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/isindex\n 'basefont', 'isindex'\n ]);\n this.unformatted = this._get_array('unformatted', []);\n this.content_unformatted = this._get_array('content_unformatted', [\n 'pre', 'textarea'\n ]);\n this.unformatted_content_delimiter = this._get_characters('unformatted_content_delimiter');\n this.indent_scripts = this._get_selection('indent_scripts', ['normal', 'keep', 'separate']);\n\n}\nOptions.prototype = new BaseOptions();\n\n\n\nmodule.exports.Options = Options;\n","/*jshint node:true */\n/*\n\n The MIT License (MIT)\n\n Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.\n\n Permission is hereby granted, free of charge, to any person\n obtaining a copy of this software and associated documentation files\n (the \"Software\"), to deal in the Software without restriction,\n including without limitation the rights to use, copy, modify, merge,\n publish, distribute, sublicense, and/or sell copies of the Software,\n and to permit persons to whom the Software is furnished to do so,\n subject to the following conditions:\n\n The above copyright notice and this permission notice shall be\n included in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n*/\n\n'use strict';\n\nvar BaseTokenizer = require('../core/tokenizer').Tokenizer;\nvar BASETOKEN = require('../core/tokenizer').TOKEN;\nvar Directives = require('../core/directives').Directives;\nvar TemplatablePattern = require('../core/templatablepattern').TemplatablePattern;\nvar Pattern = require('../core/pattern').Pattern;\n\nvar TOKEN = {\n TAG_OPEN: 'TK_TAG_OPEN',\n TAG_CLOSE: 'TK_TAG_CLOSE',\n ATTRIBUTE: 'TK_ATTRIBUTE',\n EQUALS: 'TK_EQUALS',\n VALUE: 'TK_VALUE',\n COMMENT: 'TK_COMMENT',\n TEXT: 'TK_TEXT',\n UNKNOWN: 'TK_UNKNOWN',\n START: BASETOKEN.START,\n RAW: BASETOKEN.RAW,\n EOF: BASETOKEN.EOF\n};\n\nvar directives_core = new Directives(/<\\!--/, /-->/);\n\nvar Tokenizer = function(input_string, options) {\n BaseTokenizer.call(this, input_string, options);\n this._current_tag_name = '';\n\n // Words end at whitespace or when a tag starts\n // if we are indenting handlebars, they are considered tags\n var templatable_reader = new TemplatablePattern(this._input).read_options(this._options);\n var pattern_reader = new Pattern(this._input);\n\n this.__patterns = {\n word: templatable_reader.until(/[\\n\\r\\t <]/),\n single_quote: templatable_reader.until_after(/'/),\n double_quote: templatable_reader.until_after(/\"/),\n attribute: templatable_reader.until(/[\\n\\r\\t =>]|\\/>/),\n element_name: templatable_reader.until(/[\\n\\r\\t >\\/]/),\n\n handlebars_comment: pattern_reader.starting_with(/{{!--/).until_after(/--}}/),\n handlebars: pattern_reader.starting_with(/{{/).until_after(/}}/),\n handlebars_open: pattern_reader.until(/[\\n\\r\\t }]/),\n handlebars_raw_close: pattern_reader.until(/}}/),\n comment: pattern_reader.starting_with(//),\n cdata: pattern_reader.starting_with(//),\n // https://en.wikipedia.org/wiki/Conditional_comment\n conditional_comment: pattern_reader.starting_with(//),\n processing: pattern_reader.starting_with(/<\\?/).until_after(/\\?>/)\n };\n\n if (this._options.indent_handlebars) {\n this.__patterns.word = this.__patterns.word.exclude('handlebars');\n }\n\n this._unformatted_content_delimiter = null;\n\n if (this._options.unformatted_content_delimiter) {\n var literal_regexp = this._input.get_literal_regexp(this._options.unformatted_content_delimiter);\n this.__patterns.unformatted_content_delimiter =\n pattern_reader.matching(literal_regexp)\n .until_after(literal_regexp);\n }\n};\nTokenizer.prototype = new BaseTokenizer();\n\nTokenizer.prototype._is_comment = function(current_token) { // jshint unused:false\n return false; //current_token.type === TOKEN.COMMENT || current_token.type === TOKEN.UNKNOWN;\n};\n\nTokenizer.prototype._is_opening = function(current_token) {\n return current_token.type === TOKEN.TAG_OPEN;\n};\n\nTokenizer.prototype._is_closing = function(current_token, open_token) {\n return current_token.type === TOKEN.TAG_CLOSE &&\n (open_token && (\n ((current_token.text === '>' || current_token.text === '/>') && open_token.text[0] === '<') ||\n (current_token.text === '}}' && open_token.text[0] === '{' && open_token.text[1] === '{')));\n};\n\nTokenizer.prototype._reset = function() {\n this._current_tag_name = '';\n};\n\nTokenizer.prototype._get_next_token = function(previous_token, open_token) { // jshint unused:false\n var token = null;\n this._readWhitespace();\n var c = this._input.peek();\n\n if (c === null) {\n return this._create_token(TOKEN.EOF, '');\n }\n\n token = token || this._read_open_handlebars(c, open_token);\n token = token || this._read_attribute(c, previous_token, open_token);\n token = token || this._read_close(c, open_token);\n token = token || this._read_raw_content(c, previous_token, open_token);\n token = token || this._read_content_word(c);\n token = token || this._read_comment_or_cdata(c);\n token = token || this._read_processing(c);\n token = token || this._read_open(c, open_token);\n token = token || this._create_token(TOKEN.UNKNOWN, this._input.next());\n\n return token;\n};\n\nTokenizer.prototype._read_comment_or_cdata = function(c) { // jshint unused:false\n var token = null;\n var resulting_string = null;\n var directives = null;\n\n if (c === '<') {\n var peek1 = this._input.peek(1);\n // We treat all comments as literals, even more than preformatted tags\n // we only look for the appropriate closing marker\n if (peek1 === '!') {\n resulting_string = this.__patterns.comment.read();\n\n // only process directive on html comments\n if (resulting_string) {\n directives = directives_core.get_directives(resulting_string);\n if (directives && directives.ignore === 'start') {\n resulting_string += directives_core.readIgnored(this._input);\n }\n } else {\n resulting_string = this.__patterns.cdata.read();\n }\n }\n\n if (resulting_string) {\n token = this._create_token(TOKEN.COMMENT, resulting_string);\n token.directives = directives;\n }\n }\n\n return token;\n};\n\nTokenizer.prototype._read_processing = function(c) { // jshint unused:false\n var token = null;\n var resulting_string = null;\n var directives = null;\n\n if (c === '<') {\n var peek1 = this._input.peek(1);\n if (peek1 === '!' || peek1 === '?') {\n resulting_string = this.__patterns.conditional_comment.read();\n resulting_string = resulting_string || this.__patterns.processing.read();\n }\n\n if (resulting_string) {\n token = this._create_token(TOKEN.COMMENT, resulting_string);\n token.directives = directives;\n }\n }\n\n return token;\n};\n\nTokenizer.prototype._read_open = function(c, open_token) {\n var resulting_string = null;\n var token = null;\n if (!open_token) {\n if (c === '<') {\n\n resulting_string = this._input.next();\n if (this._input.peek() === '/') {\n resulting_string += this._input.next();\n }\n resulting_string += this.__patterns.element_name.read();\n token = this._create_token(TOKEN.TAG_OPEN, resulting_string);\n }\n }\n return token;\n};\n\nTokenizer.prototype._read_open_handlebars = function(c, open_token) {\n var resulting_string = null;\n var token = null;\n if (!open_token) {\n if (this._options.indent_handlebars && c === '{' && this._input.peek(1) === '{') {\n if (this._input.peek(2) === '!') {\n resulting_string = this.__patterns.handlebars_comment.read();\n resulting_string = resulting_string || this.__patterns.handlebars.read();\n token = this._create_token(TOKEN.COMMENT, resulting_string);\n } else {\n resulting_string = this.__patterns.handlebars_open.read();\n token = this._create_token(TOKEN.TAG_OPEN, resulting_string);\n }\n }\n }\n return token;\n};\n\n\nTokenizer.prototype._read_close = function(c, open_token) {\n var resulting_string = null;\n var token = null;\n if (open_token) {\n if (open_token.text[0] === '<' && (c === '>' || (c === '/' && this._input.peek(1) === '>'))) {\n resulting_string = this._input.next();\n if (c === '/') { // for close tag \"/>\"\n resulting_string += this._input.next();\n }\n token = this._create_token(TOKEN.TAG_CLOSE, resulting_string);\n } else if (open_token.text[0] === '{' && c === '}' && this._input.peek(1) === '}') {\n this._input.next();\n this._input.next();\n token = this._create_token(TOKEN.TAG_CLOSE, '}}');\n }\n }\n\n return token;\n};\n\nTokenizer.prototype._read_attribute = function(c, previous_token, open_token) {\n var token = null;\n var resulting_string = '';\n if (open_token && open_token.text[0] === '<') {\n\n if (c === '=') {\n token = this._create_token(TOKEN.EQUALS, this._input.next());\n } else if (c === '\"' || c === \"'\") {\n var content = this._input.next();\n if (c === '\"') {\n content += this.__patterns.double_quote.read();\n } else {\n content += this.__patterns.single_quote.read();\n }\n token = this._create_token(TOKEN.VALUE, content);\n } else {\n resulting_string = this.__patterns.attribute.read();\n\n if (resulting_string) {\n if (previous_token.type === TOKEN.EQUALS) {\n token = this._create_token(TOKEN.VALUE, resulting_string);\n } else {\n token = this._create_token(TOKEN.ATTRIBUTE, resulting_string);\n }\n }\n }\n }\n return token;\n};\n\nTokenizer.prototype._is_content_unformatted = function(tag_name) {\n // void_elements have no content and so cannot have unformatted content\n // script and style tags should always be read as unformatted content\n // finally content_unformatted and unformatted element contents are unformatted\n return this._options.void_elements.indexOf(tag_name) === -1 &&\n (this._options.content_unformatted.indexOf(tag_name) !== -1 ||\n this._options.unformatted.indexOf(tag_name) !== -1);\n};\n\n\nTokenizer.prototype._read_raw_content = function(c, previous_token, open_token) { // jshint unused:false\n var resulting_string = '';\n if (open_token && open_token.text[0] === '{') {\n resulting_string = this.__patterns.handlebars_raw_close.read();\n } else if (previous_token.type === TOKEN.TAG_CLOSE &&\n previous_token.opened.text[0] === '<' && previous_token.text[0] !== '/') {\n // ^^ empty tag has no content \n var tag_name = previous_token.opened.text.substr(1).toLowerCase();\n if (tag_name === 'script' || tag_name === 'style') {\n // Script and style tags are allowed to have comments wrapping their content\n // or just have regular content.\n var token = this._read_comment_or_cdata(c);\n if (token) {\n token.type = TOKEN.TEXT;\n return token;\n }\n resulting_string = this._input.readUntil(new RegExp('', 'ig'));\n } else if (this._is_content_unformatted(tag_name)) {\n\n resulting_string = this._input.readUntil(new RegExp('', 'ig'));\n }\n }\n\n if (resulting_string) {\n return this._create_token(TOKEN.TEXT, resulting_string);\n }\n\n return null;\n};\n\nTokenizer.prototype._read_content_word = function(c) {\n var resulting_string = '';\n if (this._options.unformatted_content_delimiter) {\n if (c === this._options.unformatted_content_delimiter[0]) {\n resulting_string = this.__patterns.unformatted_content_delimiter.read();\n }\n }\n\n if (!resulting_string) {\n resulting_string = this.__patterns.word.read();\n }\n if (resulting_string) {\n return this._create_token(TOKEN.TEXT, resulting_string);\n }\n};\n\nmodule.exports.Tokenizer = Tokenizer;\nmodule.exports.TOKEN = TOKEN;\n","/*jshint node:true */\n/*\n\n The MIT License (MIT)\n\n Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.\n\n Permission is hereby granted, free of charge, to any person\n obtaining a copy of this software and associated documentation files\n (the \"Software\"), to deal in the Software without restriction,\n including without limitation the rights to use, copy, modify, merge,\n publish, distribute, sublicense, and/or sell copies of the Software,\n and to permit persons to whom the Software is furnished to do so,\n subject to the following conditions:\n\n The above copyright notice and this permission notice shall be\n included in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n*/\n\n'use strict';\n\nvar Options = require('../html/options').Options;\nvar Output = require('../core/output').Output;\nvar Tokenizer = require('../html/tokenizer').Tokenizer;\nvar TOKEN = require('../html/tokenizer').TOKEN;\n\nvar lineBreak = /\\r\\n|[\\r\\n]/;\nvar allLineBreaks = /\\r\\n|[\\r\\n]/g;\n\nvar Printer = function(options, base_indent_string) { //handles input/output and some other printing functions\n\n this.indent_level = 0;\n this.alignment_size = 0;\n this.max_preserve_newlines = options.max_preserve_newlines;\n this.preserve_newlines = options.preserve_newlines;\n\n this._output = new Output(options, base_indent_string);\n\n};\n\nPrinter.prototype.current_line_has_match = function(pattern) {\n return this._output.current_line.has_match(pattern);\n};\n\nPrinter.prototype.set_space_before_token = function(value, non_breaking) {\n this._output.space_before_token = value;\n this._output.non_breaking_space = non_breaking;\n};\n\nPrinter.prototype.set_wrap_point = function() {\n this._output.set_indent(this.indent_level, this.alignment_size);\n this._output.set_wrap_point();\n};\n\n\nPrinter.prototype.add_raw_token = function(token) {\n this._output.add_raw_token(token);\n};\n\nPrinter.prototype.print_preserved_newlines = function(raw_token) {\n var newlines = 0;\n if (raw_token.type !== TOKEN.TEXT && raw_token.previous.type !== TOKEN.TEXT) {\n newlines = raw_token.newlines ? 1 : 0;\n }\n\n if (this.preserve_newlines) {\n newlines = raw_token.newlines < this.max_preserve_newlines + 1 ? raw_token.newlines : this.max_preserve_newlines + 1;\n }\n for (var n = 0; n < newlines; n++) {\n this.print_newline(n > 0);\n }\n\n return newlines !== 0;\n};\n\nPrinter.prototype.traverse_whitespace = function(raw_token) {\n if (raw_token.whitespace_before || raw_token.newlines) {\n if (!this.print_preserved_newlines(raw_token)) {\n this._output.space_before_token = true;\n }\n return true;\n }\n return false;\n};\n\nPrinter.prototype.previous_token_wrapped = function() {\n return this._output.previous_token_wrapped;\n};\n\nPrinter.prototype.print_newline = function(force) {\n this._output.add_new_line(force);\n};\n\nPrinter.prototype.print_token = function(token) {\n if (token.text) {\n this._output.set_indent(this.indent_level, this.alignment_size);\n this._output.add_token(token.text);\n }\n};\n\nPrinter.prototype.indent = function() {\n this.indent_level++;\n};\n\nPrinter.prototype.get_full_indent = function(level) {\n level = this.indent_level + (level || 0);\n if (level < 1) {\n return '';\n }\n\n return this._output.get_indent_string(level);\n};\n\nvar get_type_attribute = function(start_token) {\n var result = null;\n var raw_token = start_token.next;\n\n // Search attributes for a type attribute\n while (raw_token.type !== TOKEN.EOF && start_token.closed !== raw_token) {\n if (raw_token.type === TOKEN.ATTRIBUTE && raw_token.text === 'type') {\n if (raw_token.next && raw_token.next.type === TOKEN.EQUALS &&\n raw_token.next.next && raw_token.next.next.type === TOKEN.VALUE) {\n result = raw_token.next.next.text;\n }\n break;\n }\n raw_token = raw_token.next;\n }\n\n return result;\n};\n\nvar get_custom_beautifier_name = function(tag_check, raw_token) {\n var typeAttribute = null;\n var result = null;\n\n if (!raw_token.closed) {\n return null;\n }\n\n if (tag_check === 'script') {\n typeAttribute = 'text/javascript';\n } else if (tag_check === 'style') {\n typeAttribute = 'text/css';\n }\n\n typeAttribute = get_type_attribute(raw_token) || typeAttribute;\n\n // For script and style tags that have a type attribute, only enable custom beautifiers for matching values\n // For those without a type attribute use default;\n if (typeAttribute.search('text/css') > -1) {\n result = 'css';\n } else if (typeAttribute.search(/module|((text|application|dojo)\\/(x-)?(javascript|ecmascript|jscript|livescript|(ld\\+)?json|method|aspect))/) > -1) {\n result = 'javascript';\n } else if (typeAttribute.search(/(text|application|dojo)\\/(x-)?(html)/) > -1) {\n result = 'html';\n } else if (typeAttribute.search(/test\\/null/) > -1) {\n // Test only mime-type for testing the beautifier when null is passed as beautifing function\n result = 'null';\n }\n\n return result;\n};\n\nfunction in_array(what, arr) {\n return arr.indexOf(what) !== -1;\n}\n\nfunction TagFrame(parent, parser_token, indent_level) {\n this.parent = parent || null;\n this.tag = parser_token ? parser_token.tag_name : '';\n this.indent_level = indent_level || 0;\n this.parser_token = parser_token || null;\n}\n\nfunction TagStack(printer) {\n this._printer = printer;\n this._current_frame = null;\n}\n\nTagStack.prototype.get_parser_token = function() {\n return this._current_frame ? this._current_frame.parser_token : null;\n};\n\nTagStack.prototype.record_tag = function(parser_token) { //function to record a tag and its parent in this.tags Object\n var new_frame = new TagFrame(this._current_frame, parser_token, this._printer.indent_level);\n this._current_frame = new_frame;\n};\n\nTagStack.prototype._try_pop_frame = function(frame) { //function to retrieve the opening tag to the corresponding closer\n var parser_token = null;\n\n if (frame) {\n parser_token = frame.parser_token;\n this._printer.indent_level = frame.indent_level;\n this._current_frame = frame.parent;\n }\n\n return parser_token;\n};\n\nTagStack.prototype._get_frame = function(tag_list, stop_list) { //function to retrieve the opening tag to the corresponding closer\n var frame = this._current_frame;\n\n while (frame) { //till we reach '' (the initial value);\n if (tag_list.indexOf(frame.tag) !== -1) { //if this is it use it\n break;\n } else if (stop_list && stop_list.indexOf(frame.tag) !== -1) {\n frame = null;\n break;\n }\n frame = frame.parent;\n }\n\n return frame;\n};\n\nTagStack.prototype.try_pop = function(tag, stop_list) { //function to retrieve the opening tag to the corresponding closer\n var frame = this._get_frame([tag], stop_list);\n return this._try_pop_frame(frame);\n};\n\nTagStack.prototype.indent_to_tag = function(tag_list) {\n var frame = this._get_frame(tag_list);\n if (frame) {\n this._printer.indent_level = frame.indent_level;\n }\n};\n\nfunction Beautifier(source_text, options, js_beautify, css_beautify) {\n //Wrapper function to invoke all the necessary constructors and deal with the output.\n this._source_text = source_text || '';\n options = options || {};\n this._js_beautify = js_beautify;\n this._css_beautify = css_beautify;\n this._tag_stack = null;\n\n // Allow the setting of language/file-type specific options\n // with inheritance of overall settings\n var optionHtml = new Options(options, 'html');\n\n this._options = optionHtml;\n\n this._is_wrap_attributes_force = this._options.wrap_attributes.substr(0, 'force'.length) === 'force';\n this._is_wrap_attributes_force_expand_multiline = (this._options.wrap_attributes === 'force-expand-multiline');\n this._is_wrap_attributes_force_aligned = (this._options.wrap_attributes === 'force-aligned');\n this._is_wrap_attributes_aligned_multiple = (this._options.wrap_attributes === 'aligned-multiple');\n this._is_wrap_attributes_preserve = this._options.wrap_attributes.substr(0, 'preserve'.length) === 'preserve';\n this._is_wrap_attributes_preserve_aligned = (this._options.wrap_attributes === 'preserve-aligned');\n}\n\nBeautifier.prototype.beautify = function() {\n\n // if disabled, return the input unchanged.\n if (this._options.disabled) {\n return this._source_text;\n }\n\n var source_text = this._source_text;\n var eol = this._options.eol;\n if (this._options.eol === 'auto') {\n eol = '\\n';\n if (source_text && lineBreak.test(source_text)) {\n eol = source_text.match(lineBreak)[0];\n }\n }\n\n // HACK: newline parsing inconsistent. This brute force normalizes the input.\n source_text = source_text.replace(allLineBreaks, '\\n');\n\n var baseIndentString = source_text.match(/^[\\t ]*/)[0];\n\n var last_token = {\n text: '',\n type: ''\n };\n\n var last_tag_token = new TagOpenParserToken();\n\n var printer = new Printer(this._options, baseIndentString);\n var tokens = new Tokenizer(source_text, this._options).tokenize();\n\n this._tag_stack = new TagStack(printer);\n\n var parser_token = null;\n var raw_token = tokens.next();\n while (raw_token.type !== TOKEN.EOF) {\n\n if (raw_token.type === TOKEN.TAG_OPEN || raw_token.type === TOKEN.COMMENT) {\n parser_token = this._handle_tag_open(printer, raw_token, last_tag_token, last_token);\n last_tag_token = parser_token;\n } else if ((raw_token.type === TOKEN.ATTRIBUTE || raw_token.type === TOKEN.EQUALS || raw_token.type === TOKEN.VALUE) ||\n (raw_token.type === TOKEN.TEXT && !last_tag_token.tag_complete)) {\n parser_token = this._handle_inside_tag(printer, raw_token, last_tag_token, tokens);\n } else if (raw_token.type === TOKEN.TAG_CLOSE) {\n parser_token = this._handle_tag_close(printer, raw_token, last_tag_token);\n } else if (raw_token.type === TOKEN.TEXT) {\n parser_token = this._handle_text(printer, raw_token, last_tag_token);\n } else {\n // This should never happen, but if it does. Print the raw token\n printer.add_raw_token(raw_token);\n }\n\n last_token = parser_token;\n\n raw_token = tokens.next();\n }\n var sweet_code = printer._output.get_code(eol);\n\n return sweet_code;\n};\n\nBeautifier.prototype._handle_tag_close = function(printer, raw_token, last_tag_token) {\n var parser_token = {\n text: raw_token.text,\n type: raw_token.type\n };\n printer.alignment_size = 0;\n last_tag_token.tag_complete = true;\n\n printer.set_space_before_token(raw_token.newlines || raw_token.whitespace_before !== '', true);\n if (last_tag_token.is_unformatted) {\n printer.add_raw_token(raw_token);\n } else {\n if (last_tag_token.tag_start_char === '<') {\n printer.set_space_before_token(raw_token.text[0] === '/', true); // space before />, no space before >\n if (this._is_wrap_attributes_force_expand_multiline && last_tag_token.has_wrapped_attrs) {\n printer.print_newline(false);\n }\n }\n printer.print_token(raw_token);\n\n }\n\n if (last_tag_token.indent_content &&\n !(last_tag_token.is_unformatted || last_tag_token.is_content_unformatted)) {\n printer.indent();\n\n // only indent once per opened tag\n last_tag_token.indent_content = false;\n }\n\n if (!last_tag_token.is_inline_element &&\n !(last_tag_token.is_unformatted || last_tag_token.is_content_unformatted)) {\n printer.set_wrap_point();\n }\n\n return parser_token;\n};\n\nBeautifier.prototype._handle_inside_tag = function(printer, raw_token, last_tag_token, tokens) {\n var wrapped = last_tag_token.has_wrapped_attrs;\n var parser_token = {\n text: raw_token.text,\n type: raw_token.type\n };\n\n printer.set_space_before_token(raw_token.newlines || raw_token.whitespace_before !== '', true);\n if (last_tag_token.is_unformatted) {\n printer.add_raw_token(raw_token);\n } else if (last_tag_token.tag_start_char === '{' && raw_token.type === TOKEN.TEXT) {\n // For the insides of handlebars allow newlines or a single space between open and contents\n if (printer.print_preserved_newlines(raw_token)) {\n raw_token.newlines = 0;\n printer.add_raw_token(raw_token);\n } else {\n printer.print_token(raw_token);\n }\n } else {\n if (raw_token.type === TOKEN.ATTRIBUTE) {\n printer.set_space_before_token(true);\n last_tag_token.attr_count += 1;\n } else if (raw_token.type === TOKEN.EQUALS) { //no space before =\n printer.set_space_before_token(false);\n } else if (raw_token.type === TOKEN.VALUE && raw_token.previous.type === TOKEN.EQUALS) { //no space before value\n printer.set_space_before_token(false);\n }\n\n if (raw_token.type === TOKEN.ATTRIBUTE && last_tag_token.tag_start_char === '<') {\n if (this._is_wrap_attributes_preserve || this._is_wrap_attributes_preserve_aligned) {\n printer.traverse_whitespace(raw_token);\n wrapped = wrapped || raw_token.newlines !== 0;\n }\n\n\n if (this._is_wrap_attributes_force) {\n var force_attr_wrap = last_tag_token.attr_count > 1;\n if (this._is_wrap_attributes_force_expand_multiline && last_tag_token.attr_count === 1) {\n var is_only_attribute = true;\n var peek_index = 0;\n var peek_token;\n do {\n peek_token = tokens.peek(peek_index);\n if (peek_token.type === TOKEN.ATTRIBUTE) {\n is_only_attribute = false;\n break;\n }\n peek_index += 1;\n } while (peek_index < 4 && peek_token.type !== TOKEN.EOF && peek_token.type !== TOKEN.TAG_CLOSE);\n\n force_attr_wrap = !is_only_attribute;\n }\n\n if (force_attr_wrap) {\n printer.print_newline(false);\n wrapped = true;\n }\n }\n }\n printer.print_token(raw_token);\n wrapped = wrapped || printer.previous_token_wrapped();\n last_tag_token.has_wrapped_attrs = wrapped;\n }\n return parser_token;\n};\n\nBeautifier.prototype._handle_text = function(printer, raw_token, last_tag_token) {\n var parser_token = {\n text: raw_token.text,\n type: 'TK_CONTENT'\n };\n if (last_tag_token.custom_beautifier_name) { //check if we need to format javascript\n this._print_custom_beatifier_text(printer, raw_token, last_tag_token);\n } else if (last_tag_token.is_unformatted || last_tag_token.is_content_unformatted) {\n printer.add_raw_token(raw_token);\n } else {\n printer.traverse_whitespace(raw_token);\n printer.print_token(raw_token);\n }\n return parser_token;\n};\n\nBeautifier.prototype._print_custom_beatifier_text = function(printer, raw_token, last_tag_token) {\n var local = this;\n if (raw_token.text !== '') {\n\n var text = raw_token.text,\n _beautifier,\n script_indent_level = 1,\n pre = '',\n post = '';\n if (last_tag_token.custom_beautifier_name === 'javascript' && typeof this._js_beautify === 'function') {\n _beautifier = this._js_beautify;\n } else if (last_tag_token.custom_beautifier_name === 'css' && typeof this._css_beautify === 'function') {\n _beautifier = this._css_beautify;\n } else if (last_tag_token.custom_beautifier_name === 'html') {\n _beautifier = function(html_source, options) {\n var beautifier = new Beautifier(html_source, options, local._js_beautify, local._css_beautify);\n return beautifier.beautify();\n };\n }\n\n if (this._options.indent_scripts === \"keep\") {\n script_indent_level = 0;\n } else if (this._options.indent_scripts === \"separate\") {\n script_indent_level = -printer.indent_level;\n }\n\n var indentation = printer.get_full_indent(script_indent_level);\n\n // if there is at least one empty line at the end of this text, strip it\n // we'll be adding one back after the text but before the containing tag.\n text = text.replace(/\\n[ \\t]*$/, '');\n\n // Handle the case where content is wrapped in a comment or cdata.\n if (last_tag_token.custom_beautifier_name !== 'html' &&\n text[0] === '<' && text.match(/^(|]]>)$/.exec(text);\n\n // if we start to wrap but don't finish, print raw\n if (!matched) {\n printer.add_raw_token(raw_token);\n return;\n }\n\n pre = indentation + matched[1] + '\\n';\n text = matched[4];\n if (matched[5]) {\n post = indentation + matched[5];\n }\n\n // if there is at least one empty line at the end of this text, strip it\n // we'll be adding one back after the text but before the containing tag.\n text = text.replace(/\\n[ \\t]*$/, '');\n\n if (matched[2] || matched[3].indexOf('\\n') !== -1) {\n // if the first line of the non-comment text has spaces\n // use that as the basis for indenting in null case.\n matched = matched[3].match(/[ \\t]+$/);\n if (matched) {\n raw_token.whitespace_before = matched[0];\n }\n }\n }\n\n if (text) {\n if (_beautifier) {\n\n // call the Beautifier if avaliable\n var Child_options = function() {\n this.eol = '\\n';\n };\n Child_options.prototype = this._options.raw_options;\n var child_options = new Child_options();\n text = _beautifier(indentation + text, child_options);\n } else {\n // simply indent the string otherwise\n var white = raw_token.whitespace_before;\n if (white) {\n text = text.replace(new RegExp('\\n(' + white + ')?', 'g'), '\\n');\n }\n\n text = indentation + text.replace(/\\n/g, '\\n' + indentation);\n }\n }\n\n if (pre) {\n if (!text) {\n text = pre + post;\n } else {\n text = pre + text + '\\n' + post;\n }\n }\n\n printer.print_newline(false);\n if (text) {\n raw_token.text = text;\n raw_token.whitespace_before = '';\n raw_token.newlines = 0;\n printer.add_raw_token(raw_token);\n printer.print_newline(true);\n }\n }\n};\n\nBeautifier.prototype._handle_tag_open = function(printer, raw_token, last_tag_token, last_token) {\n var parser_token = this._get_tag_open_token(raw_token);\n\n if ((last_tag_token.is_unformatted || last_tag_token.is_content_unformatted) &&\n !last_tag_token.is_empty_element &&\n raw_token.type === TOKEN.TAG_OPEN && raw_token.text.indexOf(']*)/);\n this.tag_check = tag_check_match ? tag_check_match[1] : '';\n } else {\n tag_check_match = raw_token.text.match(/^{{~?(?:[\\^]|#\\*?)?([^\\s}]+)/);\n this.tag_check = tag_check_match ? tag_check_match[1] : '';\n\n // handle \"{{#> myPartial}}\" or \"{{~#> myPartial}}\"\n if ((raw_token.text.startsWith('{{#>') || raw_token.text.startsWith('{{~#>')) && this.tag_check[0] === '>') {\n if (this.tag_check === '>' && raw_token.next !== null) {\n this.tag_check = raw_token.next.text.split(' ')[0];\n } else {\n this.tag_check = raw_token.text.split('>')[1];\n }\n }\n }\n\n this.tag_check = this.tag_check.toLowerCase();\n\n if (raw_token.type === TOKEN.COMMENT) {\n this.tag_complete = true;\n }\n\n this.is_start_tag = this.tag_check.charAt(0) !== '/';\n this.tag_name = !this.is_start_tag ? this.tag_check.substr(1) : this.tag_check;\n this.is_end_tag = !this.is_start_tag ||\n (raw_token.closed && raw_token.closed.text === '/>');\n\n // if whitespace handler ~ included (i.e. {{~#if true}}), handlebars tags start at pos 3 not pos 2\n var handlebar_starts = 2;\n if (this.tag_start_char === '{' && this.text.length >= 3) {\n if (this.text.charAt(2) === '~') {\n handlebar_starts = 3;\n }\n }\n\n // handlebars tags that don't start with # or ^ are single_tags, and so also start and end.\n this.is_end_tag = this.is_end_tag ||\n (this.tag_start_char === '{' && (this.text.length < 3 || (/[^#\\^]/.test(this.text.charAt(handlebar_starts)))));\n }\n};\n\nBeautifier.prototype._get_tag_open_token = function(raw_token) { //function to get a full tag and parse its type\n var parser_token = new TagOpenParserToken(this._tag_stack.get_parser_token(), raw_token);\n\n parser_token.alignment_size = this._options.wrap_attributes_indent_size;\n\n parser_token.is_end_tag = parser_token.is_end_tag ||\n in_array(parser_token.tag_check, this._options.void_elements);\n\n parser_token.is_empty_element = parser_token.tag_complete ||\n (parser_token.is_start_tag && parser_token.is_end_tag);\n\n parser_token.is_unformatted = !parser_token.tag_complete && in_array(parser_token.tag_check, this._options.unformatted);\n parser_token.is_content_unformatted = !parser_token.is_empty_element && in_array(parser_token.tag_check, this._options.content_unformatted);\n parser_token.is_inline_element = in_array(parser_token.tag_name, this._options.inline) || parser_token.tag_name.includes(\"-\") || parser_token.tag_start_char === '{';\n\n return parser_token;\n};\n\nBeautifier.prototype._set_tag_position = function(printer, raw_token, parser_token, last_tag_token, last_token) {\n\n if (!parser_token.is_empty_element) {\n if (parser_token.is_end_tag) { //this tag is a double tag so check for tag-ending\n parser_token.start_tag_token = this._tag_stack.try_pop(parser_token.tag_name); //remove it and all ancestors\n } else { // it's a start-tag\n // check if this tag is starting an element that has optional end element\n // and do an ending needed\n if (this._do_optional_end_element(parser_token)) {\n if (!parser_token.is_inline_element) {\n printer.print_newline(false);\n }\n }\n\n this._tag_stack.record_tag(parser_token); //push it on the tag stack\n\n if ((parser_token.tag_name === 'script' || parser_token.tag_name === 'style') &&\n !(parser_token.is_unformatted || parser_token.is_content_unformatted)) {\n parser_token.custom_beautifier_name = get_custom_beautifier_name(parser_token.tag_check, raw_token);\n }\n }\n }\n\n if (in_array(parser_token.tag_check, this._options.extra_liners)) { //check if this double needs an extra line\n printer.print_newline(false);\n if (!printer._output.just_added_blankline()) {\n printer.print_newline(true);\n }\n }\n\n if (parser_token.is_empty_element) { //if this tag name is a single tag type (either in the list or has a closing /)\n\n // if you hit an else case, reset the indent level if you are inside an:\n // 'if', 'unless', or 'each' block.\n if (parser_token.tag_start_char === '{' && parser_token.tag_check === 'else') {\n this._tag_stack.indent_to_tag(['if', 'unless', 'each']);\n parser_token.indent_content = true;\n // Don't add a newline if opening {{#if}} tag is on the current line\n var foundIfOnCurrentLine = printer.current_line_has_match(/{{#if/);\n if (!foundIfOnCurrentLine) {\n printer.print_newline(false);\n }\n }\n\n // Don't add a newline before elements that should remain where they are.\n if (parser_token.tag_name === '!--' && last_token.type === TOKEN.TAG_CLOSE &&\n last_tag_token.is_end_tag && parser_token.text.indexOf('\\n') === -1) {\n //Do nothing. Leave comments on same line.\n } else {\n if (!(parser_token.is_inline_element || parser_token.is_unformatted)) {\n printer.print_newline(false);\n }\n this._calcluate_parent_multiline(printer, parser_token);\n }\n } else if (parser_token.is_end_tag) { //this tag is a double tag so check for tag-ending\n var do_end_expand = false;\n\n // deciding whether a block is multiline should not be this hard\n do_end_expand = parser_token.start_tag_token && parser_token.start_tag_token.multiline_content;\n do_end_expand = do_end_expand || (!parser_token.is_inline_element &&\n !(last_tag_token.is_inline_element || last_tag_token.is_unformatted) &&\n !(last_token.type === TOKEN.TAG_CLOSE && parser_token.start_tag_token === last_tag_token) &&\n last_token.type !== 'TK_CONTENT'\n );\n\n if (parser_token.is_content_unformatted || parser_token.is_unformatted) {\n do_end_expand = false;\n }\n\n if (do_end_expand) {\n printer.print_newline(false);\n }\n } else { // it's a start-tag\n parser_token.indent_content = !parser_token.custom_beautifier_name;\n\n if (parser_token.tag_start_char === '<') {\n if (parser_token.tag_name === 'html') {\n parser_token.indent_content = this._options.indent_inner_html;\n } else if (parser_token.tag_name === 'head') {\n parser_token.indent_content = this._options.indent_head_inner_html;\n } else if (parser_token.tag_name === 'body') {\n parser_token.indent_content = this._options.indent_body_inner_html;\n }\n }\n\n if (!(parser_token.is_inline_element || parser_token.is_unformatted) &&\n (last_token.type !== 'TK_CONTENT' || parser_token.is_content_unformatted)) {\n printer.print_newline(false);\n }\n\n this._calcluate_parent_multiline(printer, parser_token);\n }\n};\n\nBeautifier.prototype._calcluate_parent_multiline = function(printer, parser_token) {\n if (parser_token.parent && printer._output.just_added_newline() &&\n !((parser_token.is_inline_element || parser_token.is_unformatted) && parser_token.parent.is_inline_element)) {\n parser_token.parent.multiline_content = true;\n }\n};\n\n//To be used for

tag special case:\nvar p_closers = ['address', 'article', 'aside', 'blockquote', 'details', 'div', 'dl', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'hr', 'main', 'nav', 'ol', 'p', 'pre', 'section', 'table', 'ul'];\nvar p_parent_excludes = ['a', 'audio', 'del', 'ins', 'map', 'noscript', 'video'];\n\nBeautifier.prototype._do_optional_end_element = function(parser_token) {\n var result = null;\n // NOTE: cases of \"if there is no more content in the parent element\"\n // are handled automatically by the beautifier.\n // It assumes parent or ancestor close tag closes all children.\n // https://www.w3.org/TR/html5/syntax.html#optional-tags\n if (parser_token.is_empty_element || !parser_token.is_start_tag || !parser_token.parent) {\n return;\n\n }\n\n if (parser_token.tag_name === 'body') {\n // A head element’s end tag may be omitted if the head element is not immediately followed by a space character or a comment.\n result = result || this._tag_stack.try_pop('head');\n\n //} else if (parser_token.tag_name === 'body') {\n // DONE: A body element’s end tag may be omitted if the body element is not immediately followed by a comment.\n\n } else if (parser_token.tag_name === 'li') {\n // An li element’s end tag may be omitted if the li element is immediately followed by another li element or if there is no more content in the parent element.\n result = result || this._tag_stack.try_pop('li', ['ol', 'ul']);\n\n } else if (parser_token.tag_name === 'dd' || parser_token.tag_name === 'dt') {\n // A dd element’s end tag may be omitted if the dd element is immediately followed by another dd element or a dt element, or if there is no more content in the parent element.\n // A dt element’s end tag may be omitted if the dt element is immediately followed by another dt element or a dd element.\n result = result || this._tag_stack.try_pop('dt', ['dl']);\n result = result || this._tag_stack.try_pop('dd', ['dl']);\n\n\n } else if (parser_token.parent.tag_name === 'p' && p_closers.indexOf(parser_token.tag_name) !== -1) {\n // IMPORTANT: this else-if works because p_closers has no overlap with any other element we look for in this method\n // check for the parent element is an HTML element that is not an ,

tag special case:\nvar p_closers = ['address', 'article', 'aside', 'blockquote', 'details', 'div', 'dl', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'hr', 'main', 'nav', 'ol', 'p', 'pre', 'section', 'table', 'ul'];\nvar p_parent_excludes = ['a', 'audio', 'del', 'ins', 'map', 'noscript', 'video'];\n\nBeautifier.prototype._do_optional_end_element = function(parser_token) {\n var result = null;\n // NOTE: cases of \"if there is no more content in the parent element\"\n // are handled automatically by the beautifier.\n // It assumes parent or ancestor close tag closes all children.\n // https://www.w3.org/TR/html5/syntax.html#optional-tags\n if (parser_token.is_empty_element || !parser_token.is_start_tag || !parser_token.parent) {\n return;\n\n }\n\n if (parser_token.tag_name === 'body') {\n // A head element’s end tag may be omitted if the head element is not immediately followed by a space character or a comment.\n result = result || this._tag_stack.try_pop('head');\n\n //} else if (parser_token.tag_name === 'body') {\n // DONE: A body element’s end tag may be omitted if the body element is not immediately followed by a comment.\n\n } else if (parser_token.tag_name === 'li') {\n // An li element’s end tag may be omitted if the li element is immediately followed by another li element or if there is no more content in the parent element.\n result = result || this._tag_stack.try_pop('li', ['ol', 'ul']);\n\n } else if (parser_token.tag_name === 'dd' || parser_token.tag_name === 'dt') {\n // A dd element’s end tag may be omitted if the dd element is immediately followed by another dd element or a dt element, or if there is no more content in the parent element.\n // A dt element’s end tag may be omitted if the dt element is immediately followed by another dt element or a dd element.\n result = result || this._tag_stack.try_pop('dt', ['dl']);\n result = result || this._tag_stack.try_pop('dd', ['dl']);\n\n\n } else if (parser_token.parent.tag_name === 'p' && p_closers.indexOf(parser_token.tag_name) !== -1) {\n // IMPORTANT: this else-if works because p_closers has no overlap with any other element we look for in this method\n // check for the parent element is an HTML element that is not an ,

tag special case:\nvar p_closers = ['address', 'article', 'aside', 'blockquote', 'details', 'div', 'dl', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'hr', 'main', 'nav', 'ol', 'p', 'pre', 'section', 'table', 'ul'];\nvar p_parent_excludes = ['a', 'audio', 'del', 'ins', 'map', 'noscript', 'video'];\n\nBeautifier.prototype._do_optional_end_element = function(parser_token) {\n var result = null;\n // NOTE: cases of \"if there is no more content in the parent element\"\n // are handled automatically by the beautifier.\n // It assumes parent or ancestor close tag closes all children.\n // https://www.w3.org/TR/html5/syntax.html#optional-tags\n if (parser_token.is_empty_element || !parser_token.is_start_tag || !parser_token.parent) {\n return;\n\n }\n\n if (parser_token.tag_name === 'body') {\n // A head element’s end tag may be omitted if the head element is not immediately followed by a space character or a comment.\n result = result || this._tag_stack.try_pop('head');\n\n //} else if (parser_token.tag_name === 'body') {\n // DONE: A body element’s end tag may be omitted if the body element is not immediately followed by a comment.\n\n } else if (parser_token.tag_name === 'li') {\n // An li element’s end tag may be omitted if the li element is immediately followed by another li element or if there is no more content in the parent element.\n result = result || this._tag_stack.try_pop('li', ['ol', 'ul']);\n\n } else if (parser_token.tag_name === 'dd' || parser_token.tag_name === 'dt') {\n // A dd element’s end tag may be omitted if the dd element is immediately followed by another dd element or a dt element, or if there is no more content in the parent element.\n // A dt element’s end tag may be omitted if the dt element is immediately followed by another dt element or a dd element.\n result = result || this._tag_stack.try_pop('dt', ['dl']);\n result = result || this._tag_stack.try_pop('dd', ['dl']);\n\n\n } else if (parser_token.parent.tag_name === 'p' && p_closers.indexOf(parser_token.tag_name) !== -1) {\n // IMPORTANT: this else-if works because p_closers has no overlap with any other element we look for in this method\n // check for the parent element is an HTML element that is not an ,

tag special case:\nvar p_closers = ['address', 'article', 'aside', 'blockquote', 'details', 'div', 'dl', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'hr', 'main', 'nav', 'ol', 'p', 'pre', 'section', 'table', 'ul'];\nvar p_parent_excludes = ['a', 'audio', 'del', 'ins', 'map', 'noscript', 'video'];\n\nBeautifier.prototype._do_optional_end_element = function(parser_token) {\n var result = null;\n // NOTE: cases of \"if there is no more content in the parent element\"\n // are handled automatically by the beautifier.\n // It assumes parent or ancestor close tag closes all children.\n // https://www.w3.org/TR/html5/syntax.html#optional-tags\n if (parser_token.is_empty_element || !parser_token.is_start_tag || !parser_token.parent) {\n return;\n\n }\n\n if (parser_token.tag_name === 'body') {\n // A head element’s end tag may be omitted if the head element is not immediately followed by a space character or a comment.\n result = result || this._tag_stack.try_pop('head');\n\n //} else if (parser_token.tag_name === 'body') {\n // DONE: A body element’s end tag may be omitted if the body element is not immediately followed by a comment.\n\n } else if (parser_token.tag_name === 'li') {\n // An li element’s end tag may be omitted if the li element is immediately followed by another li element or if there is no more content in the parent element.\n result = result || this._tag_stack.try_pop('li', ['ol', 'ul']);\n\n } else if (parser_token.tag_name === 'dd' || parser_token.tag_name === 'dt') {\n // A dd element’s end tag may be omitted if the dd element is immediately followed by another dd element or a dt element, or if there is no more content in the parent element.\n // A dt element’s end tag may be omitted if the dt element is immediately followed by another dt element or a dd element.\n result = result || this._tag_stack.try_pop('dt', ['dl']);\n result = result || this._tag_stack.try_pop('dd', ['dl']);\n\n\n } else if (parser_token.parent.tag_name === 'p' && p_closers.indexOf(parser_token.tag_name) !== -1) {\n // IMPORTANT: this else-if works because p_closers has no overlap with any other element we look for in this method\n // check for the parent element is an HTML element that is not an ,

tag special case:\nvar p_closers = ['address', 'article', 'aside', 'blockquote', 'details', 'div', 'dl', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'hr', 'main', 'nav', 'ol', 'p', 'pre', 'section', 'table', 'ul'];\nvar p_parent_excludes = ['a', 'audio', 'del', 'ins', 'map', 'noscript', 'video'];\n\nBeautifier.prototype._do_optional_end_element = function(parser_token) {\n var result = null;\n // NOTE: cases of \"if there is no more content in the parent element\"\n // are handled automatically by the beautifier.\n // It assumes parent or ancestor close tag closes all children.\n // https://www.w3.org/TR/html5/syntax.html#optional-tags\n if (parser_token.is_empty_element || !parser_token.is_start_tag || !parser_token.parent) {\n return;\n\n }\n\n if (parser_token.tag_name === 'body') {\n // A head element’s end tag may be omitted if the head element is not immediately followed by a space character or a comment.\n result = result || this._tag_stack.try_pop('head');\n\n //} else if (parser_token.tag_name === 'body') {\n // DONE: A body element’s end tag may be omitted if the body element is not immediately followed by a comment.\n\n } else if (parser_token.tag_name === 'li') {\n // An li element’s end tag may be omitted if the li element is immediately followed by another li element or if there is no more content in the parent element.\n result = result || this._tag_stack.try_pop('li', ['ol', 'ul']);\n\n } else if (parser_token.tag_name === 'dd' || parser_token.tag_name === 'dt') {\n // A dd element’s end tag may be omitted if the dd element is immediately followed by another dd element or a dt element, or if there is no more content in the parent element.\n // A dt element’s end tag may be omitted if the dt element is immediately followed by another dt element or a dd element.\n result = result || this._tag_stack.try_pop('dt', ['dl']);\n result = result || this._tag_stack.try_pop('dd', ['dl']);\n\n\n } else if (parser_token.parent.tag_name === 'p' && p_closers.indexOf(parser_token.tag_name) !== -1) {\n // IMPORTANT: this else-if works because p_closers has no overlap with any other element we look for in this method\n // check for the parent element is an HTML element that is not an ,