';\n var output = [];\n for (var lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {\n var lineIndex = lineNumber - visibleStartLineNumber;\n var renderLineNumber = this._getLineRenderLineNumber(lineNumber);\n if (renderLineNumber) {\n output[lineIndex] = (common\n + renderLineNumber\n + '
');\n }\n else {\n output[lineIndex] = '';\n }\n }\n this._renderResult = output;\n };\n LineNumbersOverlay.prototype.render = function (startLineNumber, lineNumber) {\n if (!this._renderResult) {\n return '';\n }\n var lineIndex = lineNumber - startLineNumber;\n if (lineIndex < 0 || lineIndex >= this._renderResult.length) {\n return '';\n }\n return this._renderResult[lineIndex];\n };\n LineNumbersOverlay.CLASS_NAME = 'line-numbers';\n return LineNumbersOverlay;\n}(DynamicViewOverlay));\nexport { LineNumbersOverlay };\n// theming\nregisterThemingParticipant(function (theme, collector) {\n var lineNumbers = theme.getColor(editorLineNumbers);\n if (lineNumbers) {\n collector.addRule(\".monaco-editor .line-numbers { color: \" + lineNumbers + \"; }\");\n }\n var activeLineNumber = theme.getColor(editorActiveLineNumber);\n if (activeLineNumber) {\n collector.addRule(\".monaco-editor .current-line ~ .line-numbers { color: \" + activeLineNumber + \"; }\");\n }\n});\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { createFastDomNode } from '../../../../base/browser/fastDomNode.js';\nimport { ViewPart } from '../../view/viewPart.js';\nvar Margin = /** @class */ (function (_super) {\n __extends(Margin, _super);\n function Margin(context) {\n var _this = _super.call(this, context) || this;\n _this._canUseLayerHinting = _this._context.configuration.editor.canUseLayerHinting;\n _this._contentLeft = _this._context.configuration.editor.layoutInfo.contentLeft;\n _this._glyphMarginLeft = _this._context.configuration.editor.layoutInfo.glyphMarginLeft;\n _this._glyphMarginWidth = _this._context.configuration.editor.layoutInfo.glyphMarginWidth;\n _this._domNode = _this._createDomNode();\n return _this;\n }\n Margin.prototype.dispose = function () {\n _super.prototype.dispose.call(this);\n };\n Margin.prototype.getDomNode = function () {\n return this._domNode;\n };\n Margin.prototype._createDomNode = function () {\n var domNode = createFastDomNode(document.createElement('div'));\n domNode.setClassName(Margin.OUTER_CLASS_NAME);\n domNode.setPosition('absolute');\n domNode.setAttribute('role', 'presentation');\n domNode.setAttribute('aria-hidden', 'true');\n this._glyphMarginBackgroundDomNode = createFastDomNode(document.createElement('div'));\n this._glyphMarginBackgroundDomNode.setClassName(Margin.CLASS_NAME);\n domNode.appendChild(this._glyphMarginBackgroundDomNode);\n return domNode;\n };\n // --- begin event handlers\n Margin.prototype.onConfigurationChanged = function (e) {\n if (e.canUseLayerHinting) {\n this._canUseLayerHinting = this._context.configuration.editor.canUseLayerHinting;\n }\n if (e.layoutInfo) {\n this._contentLeft = this._context.configuration.editor.layoutInfo.contentLeft;\n this._glyphMarginLeft = this._context.configuration.editor.layoutInfo.glyphMarginLeft;\n this._glyphMarginWidth = this._context.configuration.editor.layoutInfo.glyphMarginWidth;\n }\n return true;\n };\n Margin.prototype.onScrollChanged = function (e) {\n return _super.prototype.onScrollChanged.call(this, e) || e.scrollTopChanged;\n };\n // --- end event handlers\n Margin.prototype.prepareRender = function (ctx) {\n // Nothing to read\n };\n Margin.prototype.render = function (ctx) {\n this._domNode.setLayerHinting(this._canUseLayerHinting);\n var adjustedScrollTop = ctx.scrollTop - ctx.bigNumbersDelta;\n this._domNode.setTop(-adjustedScrollTop);\n var height = Math.min(ctx.scrollHeight, 1000000);\n this._domNode.setHeight(height);\n this._domNode.setWidth(this._contentLeft);\n this._glyphMarginBackgroundDomNode.setLeft(this._glyphMarginLeft);\n this._glyphMarginBackgroundDomNode.setWidth(this._glyphMarginWidth);\n this._glyphMarginBackgroundDomNode.setHeight(height);\n };\n Margin.CLASS_NAME = 'glyph-margin';\n Margin.OUTER_CLASS_NAME = 'margin';\n return Margin;\n}(ViewPart));\nexport { Margin };\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { CharacterClassifier } from '../core/characterClassifier.js';\nvar WordCharacterClassifier = /** @class */ (function (_super) {\n __extends(WordCharacterClassifier, _super);\n function WordCharacterClassifier(wordSeparators) {\n var _this = _super.call(this, 0 /* Regular */) || this;\n for (var i = 0, len = wordSeparators.length; i < len; i++) {\n _this.set(wordSeparators.charCodeAt(i), 2 /* WordSeparator */);\n }\n _this.set(32 /* Space */, 1 /* Whitespace */);\n _this.set(9 /* Tab */, 1 /* Whitespace */);\n return _this;\n }\n return WordCharacterClassifier;\n}(CharacterClassifier));\nexport { WordCharacterClassifier };\nfunction once(computeFn) {\n var cache = {}; // TODO@Alex unbounded cache\n return function (input) {\n if (!cache.hasOwnProperty(input)) {\n cache[input] = computeFn(input);\n }\n return cache[input];\n };\n}\nexport var getMapForWordSeparators = once(function (input) { return new WordCharacterClassifier(input); });\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport * as errors from '../../../base/common/errors.js';\nimport { Disposable, toDisposable } from '../../../base/common/lifecycle.js';\nvar ViewConfigurationChangedEvent = /** @class */ (function () {\n function ViewConfigurationChangedEvent(source) {\n this.type = 1 /* ViewConfigurationChanged */;\n this.canUseLayerHinting = source.canUseLayerHinting;\n this.pixelRatio = source.pixelRatio;\n this.editorClassName = source.editorClassName;\n this.lineHeight = source.lineHeight;\n this.readOnly = source.readOnly;\n this.accessibilitySupport = source.accessibilitySupport;\n this.emptySelectionClipboard = source.emptySelectionClipboard;\n this.copyWithSyntaxHighlighting = source.copyWithSyntaxHighlighting;\n this.layoutInfo = source.layoutInfo;\n this.fontInfo = source.fontInfo;\n this.viewInfo = source.viewInfo;\n this.wrappingInfo = source.wrappingInfo;\n }\n return ViewConfigurationChangedEvent;\n}());\nexport { ViewConfigurationChangedEvent };\nvar ViewCursorStateChangedEvent = /** @class */ (function () {\n function ViewCursorStateChangedEvent(selections) {\n this.type = 2 /* ViewCursorStateChanged */;\n this.selections = selections;\n }\n return ViewCursorStateChangedEvent;\n}());\nexport { ViewCursorStateChangedEvent };\nvar ViewDecorationsChangedEvent = /** @class */ (function () {\n function ViewDecorationsChangedEvent() {\n this.type = 3 /* ViewDecorationsChanged */;\n // Nothing to do\n }\n return ViewDecorationsChangedEvent;\n}());\nexport { ViewDecorationsChangedEvent };\nvar ViewFlushedEvent = /** @class */ (function () {\n function ViewFlushedEvent() {\n this.type = 4 /* ViewFlushed */;\n // Nothing to do\n }\n return ViewFlushedEvent;\n}());\nexport { ViewFlushedEvent };\nvar ViewFocusChangedEvent = /** @class */ (function () {\n function ViewFocusChangedEvent(isFocused) {\n this.type = 5 /* ViewFocusChanged */;\n this.isFocused = isFocused;\n }\n return ViewFocusChangedEvent;\n}());\nexport { ViewFocusChangedEvent };\nvar ViewLineMappingChangedEvent = /** @class */ (function () {\n function ViewLineMappingChangedEvent() {\n this.type = 6 /* ViewLineMappingChanged */;\n // Nothing to do\n }\n return ViewLineMappingChangedEvent;\n}());\nexport { ViewLineMappingChangedEvent };\nvar ViewLinesChangedEvent = /** @class */ (function () {\n function ViewLinesChangedEvent(fromLineNumber, toLineNumber) {\n this.type = 7 /* ViewLinesChanged */;\n this.fromLineNumber = fromLineNumber;\n this.toLineNumber = toLineNumber;\n }\n return ViewLinesChangedEvent;\n}());\nexport { ViewLinesChangedEvent };\nvar ViewLinesDeletedEvent = /** @class */ (function () {\n function ViewLinesDeletedEvent(fromLineNumber, toLineNumber) {\n this.type = 8 /* ViewLinesDeleted */;\n this.fromLineNumber = fromLineNumber;\n this.toLineNumber = toLineNumber;\n }\n return ViewLinesDeletedEvent;\n}());\nexport { ViewLinesDeletedEvent };\nvar ViewLinesInsertedEvent = /** @class */ (function () {\n function ViewLinesInsertedEvent(fromLineNumber, toLineNumber) {\n this.type = 9 /* ViewLinesInserted */;\n this.fromLineNumber = fromLineNumber;\n this.toLineNumber = toLineNumber;\n }\n return ViewLinesInsertedEvent;\n}());\nexport { ViewLinesInsertedEvent };\nvar ViewRevealRangeRequestEvent = /** @class */ (function () {\n function ViewRevealRangeRequestEvent(range, verticalType, revealHorizontal, scrollType) {\n this.type = 10 /* ViewRevealRangeRequest */;\n this.range = range;\n this.verticalType = verticalType;\n this.revealHorizontal = revealHorizontal;\n this.scrollType = scrollType;\n }\n return ViewRevealRangeRequestEvent;\n}());\nexport { ViewRevealRangeRequestEvent };\nvar ViewScrollChangedEvent = /** @class */ (function () {\n function ViewScrollChangedEvent(source) {\n this.type = 11 /* ViewScrollChanged */;\n this.scrollWidth = source.scrollWidth;\n this.scrollLeft = source.scrollLeft;\n this.scrollHeight = source.scrollHeight;\n this.scrollTop = source.scrollTop;\n this.scrollWidthChanged = source.scrollWidthChanged;\n this.scrollLeftChanged = source.scrollLeftChanged;\n this.scrollHeightChanged = source.scrollHeightChanged;\n this.scrollTopChanged = source.scrollTopChanged;\n }\n return ViewScrollChangedEvent;\n}());\nexport { ViewScrollChangedEvent };\nvar ViewTokensChangedEvent = /** @class */ (function () {\n function ViewTokensChangedEvent(ranges) {\n this.type = 12 /* ViewTokensChanged */;\n this.ranges = ranges;\n }\n return ViewTokensChangedEvent;\n}());\nexport { ViewTokensChangedEvent };\nvar ViewThemeChangedEvent = /** @class */ (function () {\n function ViewThemeChangedEvent() {\n this.type = 15 /* ViewThemeChanged */;\n }\n return ViewThemeChangedEvent;\n}());\nexport { ViewThemeChangedEvent };\nvar ViewTokensColorsChangedEvent = /** @class */ (function () {\n function ViewTokensColorsChangedEvent() {\n this.type = 13 /* ViewTokensColorsChanged */;\n // Nothing to do\n }\n return ViewTokensColorsChangedEvent;\n}());\nexport { ViewTokensColorsChangedEvent };\nvar ViewZonesChangedEvent = /** @class */ (function () {\n function ViewZonesChangedEvent() {\n this.type = 14 /* ViewZonesChanged */;\n // Nothing to do\n }\n return ViewZonesChangedEvent;\n}());\nexport { ViewZonesChangedEvent };\nvar ViewLanguageConfigurationEvent = /** @class */ (function () {\n function ViewLanguageConfigurationEvent() {\n this.type = 16 /* ViewLanguageConfigurationChanged */;\n }\n return ViewLanguageConfigurationEvent;\n}());\nexport { ViewLanguageConfigurationEvent };\nvar ViewEventEmitter = /** @class */ (function (_super) {\n __extends(ViewEventEmitter, _super);\n function ViewEventEmitter() {\n var _this = _super.call(this) || this;\n _this._listeners = [];\n _this._collector = null;\n _this._collectorCnt = 0;\n return _this;\n }\n ViewEventEmitter.prototype.dispose = function () {\n this._listeners = [];\n _super.prototype.dispose.call(this);\n };\n ViewEventEmitter.prototype._beginEmit = function () {\n this._collectorCnt++;\n if (this._collectorCnt === 1) {\n this._collector = new ViewEventsCollector();\n }\n return this._collector;\n };\n ViewEventEmitter.prototype._endEmit = function () {\n this._collectorCnt--;\n if (this._collectorCnt === 0) {\n var events = this._collector.finalize();\n this._collector = null;\n if (events.length > 0) {\n this._emit(events);\n }\n }\n };\n ViewEventEmitter.prototype._emit = function (events) {\n var listeners = this._listeners.slice(0);\n for (var i = 0, len = listeners.length; i < len; i++) {\n safeInvokeListener(listeners[i], events);\n }\n };\n ViewEventEmitter.prototype.addEventListener = function (listener) {\n var _this = this;\n this._listeners.push(listener);\n return toDisposable(function () {\n var listeners = _this._listeners;\n for (var i = 0, len = listeners.length; i < len; i++) {\n if (listeners[i] === listener) {\n listeners.splice(i, 1);\n break;\n }\n }\n });\n };\n return ViewEventEmitter;\n}(Disposable));\nexport { ViewEventEmitter };\nvar ViewEventsCollector = /** @class */ (function () {\n function ViewEventsCollector() {\n this._eventsLen = 0;\n this._events = [];\n this._eventsLen = 0;\n }\n ViewEventsCollector.prototype.emit = function (event) {\n this._events[this._eventsLen++] = event;\n };\n ViewEventsCollector.prototype.finalize = function () {\n var result = this._events;\n this._events = [];\n return result;\n };\n return ViewEventsCollector;\n}());\nexport { ViewEventsCollector };\nfunction safeInvokeListener(listener, events) {\n try {\n listener(events);\n }\n catch (e) {\n errors.onUnexpectedError(e);\n }\n}\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport './textAreaHandler.css';\nimport * as browser from '../../../base/browser/browser.js';\nimport { createFastDomNode } from '../../../base/browser/fastDomNode.js';\nimport * as platform from '../../../base/common/platform.js';\nimport * as strings from '../../../base/common/strings.js';\nimport { Configuration } from '../config/configuration.js';\nimport { CopyOptions, TextAreaInput } from './textAreaInput.js';\nimport { PagedScreenReaderStrategy, TextAreaState } from './textAreaState.js';\nimport { PartFingerprints, ViewPart } from '../view/viewPart.js';\nimport { LineNumbersOverlay } from '../viewParts/lineNumbers/lineNumbers.js';\nimport { Margin } from '../viewParts/margin/margin.js';\nimport { getMapForWordSeparators } from '../../common/controller/wordCharacterClassifier.js';\nimport { Position } from '../../common/core/position.js';\nimport { Range } from '../../common/core/range.js';\nimport { Selection } from '../../common/core/selection.js';\nimport * as viewEvents from '../../common/view/viewEvents.js';\nvar VisibleTextAreaData = /** @class */ (function () {\n function VisibleTextAreaData(top, left, width) {\n this.top = top;\n this.left = left;\n this.width = width;\n }\n VisibleTextAreaData.prototype.setWidth = function (width) {\n return new VisibleTextAreaData(this.top, this.left, width);\n };\n return VisibleTextAreaData;\n}());\nvar canUseZeroSizeTextarea = (browser.isEdgeOrIE || browser.isFirefox);\n/**\n * Every time we write to the clipboard, we record a bit of extra metadata here.\n * Every time we read from the cipboard, if the text matches our last written text,\n * we can fetch the previous metadata.\n */\nvar LocalClipboardMetadataManager = /** @class */ (function () {\n function LocalClipboardMetadataManager() {\n this._lastState = null;\n }\n LocalClipboardMetadataManager.prototype.set = function (state) {\n this._lastState = state;\n };\n LocalClipboardMetadataManager.prototype.get = function (pastedText) {\n if (this._lastState && this._lastState.lastCopiedValue === pastedText) {\n // match!\n return this._lastState;\n }\n this._lastState = null;\n return null;\n };\n LocalClipboardMetadataManager.INSTANCE = new LocalClipboardMetadataManager();\n return LocalClipboardMetadataManager;\n}());\nvar TextAreaHandler = /** @class */ (function (_super) {\n __extends(TextAreaHandler, _super);\n function TextAreaHandler(context, viewController, viewHelper) {\n var _this = _super.call(this, context) || this;\n // --- end view API\n _this._primaryCursorVisibleRange = null;\n _this._viewController = viewController;\n _this._viewHelper = viewHelper;\n var conf = _this._context.configuration.editor;\n _this._accessibilitySupport = conf.accessibilitySupport;\n _this._contentLeft = conf.layoutInfo.contentLeft;\n _this._contentWidth = conf.layoutInfo.contentWidth;\n _this._contentHeight = conf.layoutInfo.contentHeight;\n _this._scrollLeft = 0;\n _this._scrollTop = 0;\n _this._fontInfo = conf.fontInfo;\n _this._lineHeight = conf.lineHeight;\n _this._emptySelectionClipboard = conf.emptySelectionClipboard;\n _this._copyWithSyntaxHighlighting = conf.copyWithSyntaxHighlighting;\n _this._visibleTextArea = null;\n _this._selections = [new Selection(1, 1, 1, 1)];\n // Text Area (The focus will always be in the textarea when the cursor is blinking)\n _this.textArea = createFastDomNode(document.createElement('textarea'));\n PartFingerprints.write(_this.textArea, 6 /* TextArea */);\n _this.textArea.setClassName('inputarea');\n _this.textArea.setAttribute('wrap', 'off');\n _this.textArea.setAttribute('autocorrect', 'off');\n _this.textArea.setAttribute('autocapitalize', 'off');\n _this.textArea.setAttribute('autocomplete', 'off');\n _this.textArea.setAttribute('spellcheck', 'false');\n _this.textArea.setAttribute('aria-label', conf.viewInfo.ariaLabel);\n _this.textArea.setAttribute('role', 'textbox');\n _this.textArea.setAttribute('aria-multiline', 'true');\n _this.textArea.setAttribute('aria-haspopup', 'false');\n _this.textArea.setAttribute('aria-autocomplete', 'both');\n _this.textAreaCover = createFastDomNode(document.createElement('div'));\n _this.textAreaCover.setPosition('absolute');\n var simpleModel = {\n getLineCount: function () {\n return _this._context.model.getLineCount();\n },\n getLineMaxColumn: function (lineNumber) {\n return _this._context.model.getLineMaxColumn(lineNumber);\n },\n getValueInRange: function (range, eol) {\n return _this._context.model.getValueInRange(range, eol);\n }\n };\n var textAreaInputHost = {\n getPlainTextToCopy: function () {\n var rawWhatToCopy = _this._context.model.getPlainTextToCopy(_this._selections, _this._emptySelectionClipboard, platform.isWindows);\n var newLineCharacter = _this._context.model.getEOL();\n var isFromEmptySelection = (_this._emptySelectionClipboard && _this._selections.length === 1 && _this._selections[0].isEmpty());\n var multicursorText = (Array.isArray(rawWhatToCopy) ? rawWhatToCopy : null);\n var whatToCopy = (Array.isArray(rawWhatToCopy) ? rawWhatToCopy.join(newLineCharacter) : rawWhatToCopy);\n var metadata = null;\n if (isFromEmptySelection || multicursorText) {\n // Only store the non-default metadata\n // When writing \"LINE\\r\\n\" to the clipboard and then pasting,\n // Firefox pastes \"LINE\\n\", so let's work around this quirk\n var lastCopiedValue = (browser.isFirefox ? whatToCopy.replace(/\\r\\n/g, '\\n') : whatToCopy);\n metadata = {\n lastCopiedValue: lastCopiedValue,\n isFromEmptySelection: (_this._emptySelectionClipboard && _this._selections.length === 1 && _this._selections[0].isEmpty()),\n multicursorText: multicursorText\n };\n }\n LocalClipboardMetadataManager.INSTANCE.set(metadata);\n return whatToCopy;\n },\n getHTMLToCopy: function () {\n if (!_this._copyWithSyntaxHighlighting && !CopyOptions.forceCopyWithSyntaxHighlighting) {\n return null;\n }\n return _this._context.model.getHTMLToCopy(_this._selections, _this._emptySelectionClipboard);\n },\n getScreenReaderContent: function (currentState) {\n if (browser.isIPad) {\n // Do not place anything in the textarea for the iPad\n return TextAreaState.EMPTY;\n }\n if (_this._accessibilitySupport === 1 /* Disabled */) {\n // We know for a fact that a screen reader is not attached\n // On OSX, we write the character before the cursor to allow for \"long-press\" composition\n // Also on OSX, we write the word before the cursor to allow for the Accessibility Keyboard to give good hints\n if (platform.isMacintosh) {\n var selection = _this._selections[0];\n if (selection.isEmpty()) {\n var position = selection.getStartPosition();\n var textBefore = _this._getWordBeforePosition(position);\n if (textBefore.length === 0) {\n textBefore = _this._getCharacterBeforePosition(position);\n }\n if (textBefore.length > 0) {\n return new TextAreaState(textBefore, textBefore.length, textBefore.length, position, position);\n }\n }\n }\n return TextAreaState.EMPTY;\n }\n return PagedScreenReaderStrategy.fromEditorSelection(currentState, simpleModel, _this._selections[0], _this._accessibilitySupport === 0 /* Unknown */);\n },\n deduceModelPosition: function (viewAnchorPosition, deltaOffset, lineFeedCnt) {\n return _this._context.model.deduceModelPositionRelativeToViewPosition(viewAnchorPosition, deltaOffset, lineFeedCnt);\n }\n };\n _this._textAreaInput = _this._register(new TextAreaInput(textAreaInputHost, _this.textArea));\n _this._register(_this._textAreaInput.onKeyDown(function (e) {\n _this._viewController.emitKeyDown(e);\n }));\n _this._register(_this._textAreaInput.onKeyUp(function (e) {\n _this._viewController.emitKeyUp(e);\n }));\n _this._register(_this._textAreaInput.onPaste(function (e) {\n var metadata = LocalClipboardMetadataManager.INSTANCE.get(e.text);\n var pasteOnNewLine = false;\n var multicursorText = null;\n if (metadata) {\n pasteOnNewLine = (_this._emptySelectionClipboard && metadata.isFromEmptySelection);\n multicursorText = metadata.multicursorText;\n }\n _this._viewController.paste('keyboard', e.text, pasteOnNewLine, multicursorText);\n }));\n _this._register(_this._textAreaInput.onCut(function () {\n _this._viewController.cut('keyboard');\n }));\n _this._register(_this._textAreaInput.onType(function (e) {\n if (e.replaceCharCnt) {\n _this._viewController.replacePreviousChar('keyboard', e.text, e.replaceCharCnt);\n }\n else {\n _this._viewController.type('keyboard', e.text);\n }\n }));\n _this._register(_this._textAreaInput.onSelectionChangeRequest(function (modelSelection) {\n _this._viewController.setSelection('keyboard', modelSelection);\n }));\n _this._register(_this._textAreaInput.onCompositionStart(function () {\n var lineNumber = _this._selections[0].startLineNumber;\n var column = _this._selections[0].startColumn;\n _this._context.privateViewEventBus.emit(new viewEvents.ViewRevealRangeRequestEvent(new Range(lineNumber, column, lineNumber, column), 0 /* Simple */, true, 1 /* Immediate */));\n // Find range pixel position\n var visibleRange = _this._viewHelper.visibleRangeForPositionRelativeToEditor(lineNumber, column);\n if (visibleRange) {\n _this._visibleTextArea = new VisibleTextAreaData(_this._context.viewLayout.getVerticalOffsetForLineNumber(lineNumber), visibleRange.left, canUseZeroSizeTextarea ? 0 : 1);\n _this._render();\n }\n // Show the textarea\n _this.textArea.setClassName('inputarea ime-input');\n _this._viewController.compositionStart('keyboard');\n }));\n _this._register(_this._textAreaInput.onCompositionUpdate(function (e) {\n if (browser.isEdgeOrIE) {\n // Due to isEdgeOrIE (where the textarea was not cleared initially)\n // we cannot assume the text consists only of the composited text\n _this._visibleTextArea = _this._visibleTextArea.setWidth(0);\n }\n else {\n // adjust width by its size\n _this._visibleTextArea = _this._visibleTextArea.setWidth(measureText(e.data, _this._fontInfo));\n }\n _this._render();\n }));\n _this._register(_this._textAreaInput.onCompositionEnd(function () {\n _this._visibleTextArea = null;\n _this._render();\n _this.textArea.setClassName('inputarea');\n _this._viewController.compositionEnd('keyboard');\n }));\n _this._register(_this._textAreaInput.onFocus(function () {\n _this._context.privateViewEventBus.emit(new viewEvents.ViewFocusChangedEvent(true));\n }));\n _this._register(_this._textAreaInput.onBlur(function () {\n _this._context.privateViewEventBus.emit(new viewEvents.ViewFocusChangedEvent(false));\n }));\n return _this;\n }\n TextAreaHandler.prototype.dispose = function () {\n _super.prototype.dispose.call(this);\n };\n TextAreaHandler.prototype._getWordBeforePosition = function (position) {\n var lineContent = this._context.model.getLineContent(position.lineNumber);\n var wordSeparators = getMapForWordSeparators(this._context.configuration.editor.wordSeparators);\n var column = position.column;\n var distance = 0;\n while (column > 1) {\n var charCode = lineContent.charCodeAt(column - 2);\n var charClass = wordSeparators.get(charCode);\n if (charClass !== 0 /* Regular */ || distance > 50) {\n return lineContent.substring(column - 1, position.column - 1);\n }\n distance++;\n column--;\n }\n return lineContent.substring(0, position.column - 1);\n };\n TextAreaHandler.prototype._getCharacterBeforePosition = function (position) {\n if (position.column > 1) {\n var lineContent = this._context.model.getLineContent(position.lineNumber);\n var charBefore = lineContent.charAt(position.column - 2);\n if (!strings.isHighSurrogate(charBefore.charCodeAt(0))) {\n return charBefore;\n }\n }\n return '';\n };\n // --- begin event handlers\n TextAreaHandler.prototype.onConfigurationChanged = function (e) {\n var conf = this._context.configuration.editor;\n if (e.fontInfo) {\n this._fontInfo = conf.fontInfo;\n }\n if (e.viewInfo) {\n this.textArea.setAttribute('aria-label', conf.viewInfo.ariaLabel);\n }\n if (e.layoutInfo) {\n this._contentLeft = conf.layoutInfo.contentLeft;\n this._contentWidth = conf.layoutInfo.contentWidth;\n this._contentHeight = conf.layoutInfo.contentHeight;\n }\n if (e.lineHeight) {\n this._lineHeight = conf.lineHeight;\n }\n if (e.accessibilitySupport) {\n this._accessibilitySupport = conf.accessibilitySupport;\n this._textAreaInput.writeScreenReaderContent('strategy changed');\n }\n if (e.emptySelectionClipboard) {\n this._emptySelectionClipboard = conf.emptySelectionClipboard;\n }\n if (e.copyWithSyntaxHighlighting) {\n this._copyWithSyntaxHighlighting = conf.copyWithSyntaxHighlighting;\n }\n return true;\n };\n TextAreaHandler.prototype.onCursorStateChanged = function (e) {\n this._selections = e.selections.slice(0);\n this._textAreaInput.writeScreenReaderContent('selection changed');\n return true;\n };\n TextAreaHandler.prototype.onDecorationsChanged = function (e) {\n // true for inline decorations that can end up relayouting text\n return true;\n };\n TextAreaHandler.prototype.onFlushed = function (e) {\n return true;\n };\n TextAreaHandler.prototype.onLinesChanged = function (e) {\n return true;\n };\n TextAreaHandler.prototype.onLinesDeleted = function (e) {\n return true;\n };\n TextAreaHandler.prototype.onLinesInserted = function (e) {\n return true;\n };\n TextAreaHandler.prototype.onScrollChanged = function (e) {\n this._scrollLeft = e.scrollLeft;\n this._scrollTop = e.scrollTop;\n return true;\n };\n TextAreaHandler.prototype.onZonesChanged = function (e) {\n return true;\n };\n // --- end event handlers\n // --- begin view API\n TextAreaHandler.prototype.isFocused = function () {\n return this._textAreaInput.isFocused();\n };\n TextAreaHandler.prototype.focusTextArea = function () {\n this._textAreaInput.focusTextArea();\n };\n TextAreaHandler.prototype.prepareRender = function (ctx) {\n if (this._accessibilitySupport === 2 /* Enabled */) {\n // Do not move the textarea with the cursor, as this generates accessibility events that might confuse screen readers\n // See https://github.com/Microsoft/vscode/issues/26730\n this._primaryCursorVisibleRange = null;\n }\n else {\n var primaryCursorPosition = new Position(this._selections[0].positionLineNumber, this._selections[0].positionColumn);\n this._primaryCursorVisibleRange = ctx.visibleRangeForPosition(primaryCursorPosition);\n }\n };\n TextAreaHandler.prototype.render = function (ctx) {\n this._textAreaInput.writeScreenReaderContent('render');\n this._render();\n };\n TextAreaHandler.prototype._render = function () {\n if (this._visibleTextArea) {\n // The text area is visible for composition reasons\n this._renderInsideEditor(this._visibleTextArea.top - this._scrollTop, this._contentLeft + this._visibleTextArea.left - this._scrollLeft, this._visibleTextArea.width, this._lineHeight, true);\n return;\n }\n if (!this._primaryCursorVisibleRange) {\n // The primary cursor is outside the viewport => place textarea to the top left\n this._renderAtTopLeft();\n return;\n }\n var left = this._contentLeft + this._primaryCursorVisibleRange.left - this._scrollLeft;\n if (left < this._contentLeft || left > this._contentLeft + this._contentWidth) {\n // cursor is outside the viewport\n this._renderAtTopLeft();\n return;\n }\n var top = this._context.viewLayout.getVerticalOffsetForLineNumber(this._selections[0].positionLineNumber) - this._scrollTop;\n if (top < 0 || top > this._contentHeight) {\n // cursor is outside the viewport\n this._renderAtTopLeft();\n return;\n }\n // The primary cursor is in the viewport (at least vertically) => place textarea on the cursor\n this._renderInsideEditor(top, left, canUseZeroSizeTextarea ? 0 : 1, canUseZeroSizeTextarea ? 0 : 1, false);\n };\n TextAreaHandler.prototype._renderInsideEditor = function (top, left, width, height, useEditorFont) {\n var ta = this.textArea;\n var tac = this.textAreaCover;\n if (useEditorFont) {\n Configuration.applyFontInfo(ta, this._fontInfo);\n }\n else {\n ta.setFontSize(1);\n ta.setLineHeight(this._fontInfo.lineHeight);\n }\n ta.setTop(top);\n ta.setLeft(left);\n ta.setWidth(width);\n ta.setHeight(height);\n tac.setTop(0);\n tac.setLeft(0);\n tac.setWidth(0);\n tac.setHeight(0);\n };\n TextAreaHandler.prototype._renderAtTopLeft = function () {\n var ta = this.textArea;\n var tac = this.textAreaCover;\n Configuration.applyFontInfo(ta, this._fontInfo);\n ta.setTop(0);\n ta.setLeft(0);\n tac.setTop(0);\n tac.setLeft(0);\n if (canUseZeroSizeTextarea) {\n ta.setWidth(0);\n ta.setHeight(0);\n tac.setWidth(0);\n tac.setHeight(0);\n return;\n }\n // (in WebKit the textarea is 1px by 1px because it cannot handle input to a 0x0 textarea)\n // specifically, when doing Korean IME, setting the textarea to 0x0 breaks IME badly.\n ta.setWidth(1);\n ta.setHeight(1);\n tac.setWidth(1);\n tac.setHeight(1);\n if (this._context.configuration.editor.viewInfo.glyphMargin) {\n tac.setClassName('monaco-editor-background textAreaCover ' + Margin.OUTER_CLASS_NAME);\n }\n else {\n if (this._context.configuration.editor.viewInfo.renderLineNumbers !== 0 /* Off */) {\n tac.setClassName('monaco-editor-background textAreaCover ' + LineNumbersOverlay.CLASS_NAME);\n }\n else {\n tac.setClassName('monaco-editor-background textAreaCover');\n }\n }\n };\n return TextAreaHandler;\n}(ViewPart));\nexport { TextAreaHandler };\nfunction measureText(text, fontInfo) {\n // adjust width by its size\n var canvasElem = document.createElement('canvas');\n var context = canvasElem.getContext('2d');\n context.font = createFontString(fontInfo);\n var metrics = context.measureText(text);\n if (browser.isFirefox) {\n return metrics.width + 2; // +2 for Japanese...\n }\n else {\n return metrics.width;\n }\n}\nfunction createFontString(bareFontInfo) {\n return doCreateFontString('normal', bareFontInfo.fontWeight, bareFontInfo.fontSize, bareFontInfo.lineHeight, bareFontInfo.fontFamily);\n}\nfunction doCreateFontString(fontStyle, fontWeight, fontSize, lineHeight, fontFamily) {\n // The full font syntax is:\n // style | variant | weight | stretch | size/line-height | fontFamily\n // (https://developer.mozilla.org/en-US/docs/Web/CSS/font)\n // But it appears Edge and IE11 cannot properly parse `stretch`.\n return fontStyle + \" normal \" + fontWeight + \" \" + fontSize + \"px / \" + lineHeight + \"px \" + fontFamily;\n}\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport { onUnexpectedError } from '../../../base/common/errors.js';\nvar EditStackElement = /** @class */ (function () {\n function EditStackElement(beforeVersionId, beforeCursorState) {\n this.beforeVersionId = beforeVersionId;\n this.beforeCursorState = beforeCursorState;\n this.afterCursorState = null;\n this.afterVersionId = -1;\n this.editOperations = [];\n }\n EditStackElement.prototype.undo = function (model) {\n // Apply all operations in reverse order\n for (var i = this.editOperations.length - 1; i >= 0; i--) {\n this.editOperations[i] = {\n operations: model.applyEdits(this.editOperations[i].operations)\n };\n }\n };\n EditStackElement.prototype.redo = function (model) {\n // Apply all operations\n for (var i = 0; i < this.editOperations.length; i++) {\n this.editOperations[i] = {\n operations: model.applyEdits(this.editOperations[i].operations)\n };\n }\n };\n return EditStackElement;\n}());\nfunction getModelEOL(model) {\n var eol = model.getEOL();\n if (eol === '\\n') {\n return 0 /* LF */;\n }\n else {\n return 1 /* CRLF */;\n }\n}\nvar EOLStackElement = /** @class */ (function () {\n function EOLStackElement(beforeVersionId, setEOL) {\n this.beforeVersionId = beforeVersionId;\n this.beforeCursorState = null;\n this.afterCursorState = null;\n this.afterVersionId = -1;\n this.eol = setEOL;\n }\n EOLStackElement.prototype.undo = function (model) {\n var redoEOL = getModelEOL(model);\n model.setEOL(this.eol);\n this.eol = redoEOL;\n };\n EOLStackElement.prototype.redo = function (model) {\n var undoEOL = getModelEOL(model);\n model.setEOL(this.eol);\n this.eol = undoEOL;\n };\n return EOLStackElement;\n}());\nvar EditStack = /** @class */ (function () {\n function EditStack(model) {\n this.model = model;\n this.currentOpenStackElement = null;\n this.past = [];\n this.future = [];\n }\n EditStack.prototype.pushStackElement = function () {\n if (this.currentOpenStackElement !== null) {\n this.past.push(this.currentOpenStackElement);\n this.currentOpenStackElement = null;\n }\n };\n EditStack.prototype.clear = function () {\n this.currentOpenStackElement = null;\n this.past = [];\n this.future = [];\n };\n EditStack.prototype.pushEOL = function (eol) {\n // No support for parallel universes :(\n this.future = [];\n if (this.currentOpenStackElement) {\n this.pushStackElement();\n }\n var prevEOL = getModelEOL(this.model);\n var stackElement = new EOLStackElement(this.model.getAlternativeVersionId(), prevEOL);\n this.model.setEOL(eol);\n stackElement.afterVersionId = this.model.getVersionId();\n this.currentOpenStackElement = stackElement;\n this.pushStackElement();\n };\n EditStack.prototype.pushEditOperation = function (beforeCursorState, editOperations, cursorStateComputer) {\n // No support for parallel universes :(\n this.future = [];\n var stackElement = null;\n if (this.currentOpenStackElement) {\n if (this.currentOpenStackElement instanceof EditStackElement) {\n stackElement = this.currentOpenStackElement;\n }\n else {\n this.pushStackElement();\n }\n }\n if (!this.currentOpenStackElement) {\n stackElement = new EditStackElement(this.model.getAlternativeVersionId(), beforeCursorState);\n this.currentOpenStackElement = stackElement;\n }\n var inverseEditOperation = {\n operations: this.model.applyEdits(editOperations)\n };\n stackElement.editOperations.push(inverseEditOperation);\n stackElement.afterCursorState = EditStack._computeCursorState(cursorStateComputer, inverseEditOperation.operations);\n stackElement.afterVersionId = this.model.getVersionId();\n return stackElement.afterCursorState;\n };\n EditStack._computeCursorState = function (cursorStateComputer, inverseEditOperations) {\n try {\n return cursorStateComputer ? cursorStateComputer(inverseEditOperations) : null;\n }\n catch (e) {\n onUnexpectedError(e);\n return null;\n }\n };\n EditStack.prototype.undo = function () {\n this.pushStackElement();\n if (this.past.length > 0) {\n var pastStackElement = this.past.pop();\n try {\n pastStackElement.undo(this.model);\n }\n catch (e) {\n onUnexpectedError(e);\n this.clear();\n return null;\n }\n this.future.push(pastStackElement);\n return {\n selections: pastStackElement.beforeCursorState,\n recordedVersionId: pastStackElement.beforeVersionId\n };\n }\n return null;\n };\n EditStack.prototype.canUndo = function () {\n return (this.past.length > 0) || this.currentOpenStackElement !== null;\n };\n EditStack.prototype.redo = function () {\n if (this.future.length > 0) {\n var futureStackElement = this.future.pop();\n try {\n futureStackElement.redo(this.model);\n }\n catch (e) {\n onUnexpectedError(e);\n this.clear();\n return null;\n }\n this.past.push(futureStackElement);\n return {\n selections: futureStackElement.afterCursorState,\n recordedVersionId: futureStackElement.afterVersionId\n };\n }\n return null;\n };\n EditStack.prototype.canRedo = function () {\n return (this.future.length > 0);\n };\n return EditStack;\n}());\nexport { EditStack };\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nvar SpacesDiffResult = /** @class */ (function () {\n function SpacesDiffResult() {\n }\n return SpacesDiffResult;\n}());\n/**\n * Compute the diff in spaces between two line's indentation.\n */\nfunction spacesDiff(a, aLength, b, bLength, result) {\n result.spacesDiff = 0;\n result.looksLikeAlignment = false;\n // This can go both ways (e.g.):\n // - a: \"\\t\"\n // - b: \"\\t \"\n // => This should count 1 tab and 4 spaces\n var i;\n for (i = 0; i < aLength && i < bLength; i++) {\n var aCharCode = a.charCodeAt(i);\n var bCharCode = b.charCodeAt(i);\n if (aCharCode !== bCharCode) {\n break;\n }\n }\n var aSpacesCnt = 0, aTabsCount = 0;\n for (var j = i; j < aLength; j++) {\n var aCharCode = a.charCodeAt(j);\n if (aCharCode === 32 /* Space */) {\n aSpacesCnt++;\n }\n else {\n aTabsCount++;\n }\n }\n var bSpacesCnt = 0, bTabsCount = 0;\n for (var j = i; j < bLength; j++) {\n var bCharCode = b.charCodeAt(j);\n if (bCharCode === 32 /* Space */) {\n bSpacesCnt++;\n }\n else {\n bTabsCount++;\n }\n }\n if (aSpacesCnt > 0 && aTabsCount > 0) {\n return;\n }\n if (bSpacesCnt > 0 && bTabsCount > 0) {\n return;\n }\n var tabsDiff = Math.abs(aTabsCount - bTabsCount);\n var spacesDiff = Math.abs(aSpacesCnt - bSpacesCnt);\n if (tabsDiff === 0) {\n // check if the indentation difference might be caused by alignment reasons\n // sometime folks like to align their code, but this should not be used as a hint\n result.spacesDiff = spacesDiff;\n if (spacesDiff > 0 && 0 <= bSpacesCnt - 1 && bSpacesCnt - 1 < a.length && bSpacesCnt < b.length) {\n if (b.charCodeAt(bSpacesCnt) !== 32 /* Space */ && a.charCodeAt(bSpacesCnt - 1) === 32 /* Space */) {\n // This looks like an alignment desire: e.g.\n // const a = b + c,\n // d = b - c;\n result.looksLikeAlignment = true;\n }\n }\n return;\n }\n if (spacesDiff % tabsDiff === 0) {\n result.spacesDiff = spacesDiff / tabsDiff;\n return;\n }\n}\nexport function guessIndentation(source, defaultTabSize, defaultInsertSpaces) {\n // Look at most at the first 10k lines\n var linesCount = Math.min(source.getLineCount(), 10000);\n var linesIndentedWithTabsCount = 0; // number of lines that contain at least one tab in indentation\n var linesIndentedWithSpacesCount = 0; // number of lines that contain only spaces in indentation\n var previousLineText = ''; // content of latest line that contained non-whitespace chars\n var previousLineIndentation = 0; // index at which latest line contained the first non-whitespace char\n var ALLOWED_TAB_SIZE_GUESSES = [2, 4, 6, 8, 3, 5, 7]; // prefer even guesses for `tabSize`, limit to [2, 8].\n var MAX_ALLOWED_TAB_SIZE_GUESS = 8; // max(ALLOWED_TAB_SIZE_GUESSES) = 8\n var spacesDiffCount = [0, 0, 0, 0, 0, 0, 0, 0, 0]; // `tabSize` scores\n var tmp = new SpacesDiffResult();\n for (var lineNumber = 1; lineNumber <= linesCount; lineNumber++) {\n var currentLineLength = source.getLineLength(lineNumber);\n var currentLineText = source.getLineContent(lineNumber);\n // if the text buffer is chunk based, so long lines are cons-string, v8 will flattern the string when we check charCode.\n // checking charCode on chunks directly is cheaper.\n var useCurrentLineText = (currentLineLength <= 65536);\n var currentLineHasContent = false; // does `currentLineText` contain non-whitespace chars\n var currentLineIndentation = 0; // index at which `currentLineText` contains the first non-whitespace char\n var currentLineSpacesCount = 0; // count of spaces found in `currentLineText` indentation\n var currentLineTabsCount = 0; // count of tabs found in `currentLineText` indentation\n for (var j = 0, lenJ = currentLineLength; j < lenJ; j++) {\n var charCode = (useCurrentLineText ? currentLineText.charCodeAt(j) : source.getLineCharCode(lineNumber, j));\n if (charCode === 9 /* Tab */) {\n currentLineTabsCount++;\n }\n else if (charCode === 32 /* Space */) {\n currentLineSpacesCount++;\n }\n else {\n // Hit non whitespace character on this line\n currentLineHasContent = true;\n currentLineIndentation = j;\n break;\n }\n }\n // Ignore empty or only whitespace lines\n if (!currentLineHasContent) {\n continue;\n }\n if (currentLineTabsCount > 0) {\n linesIndentedWithTabsCount++;\n }\n else if (currentLineSpacesCount > 1) {\n linesIndentedWithSpacesCount++;\n }\n spacesDiff(previousLineText, previousLineIndentation, currentLineText, currentLineIndentation, tmp);\n if (tmp.looksLikeAlignment) {\n // skip this line entirely\n continue;\n }\n var currentSpacesDiff = tmp.spacesDiff;\n if (currentSpacesDiff <= MAX_ALLOWED_TAB_SIZE_GUESS) {\n spacesDiffCount[currentSpacesDiff]++;\n }\n previousLineText = currentLineText;\n previousLineIndentation = currentLineIndentation;\n }\n var insertSpaces = defaultInsertSpaces;\n if (linesIndentedWithTabsCount !== linesIndentedWithSpacesCount) {\n insertSpaces = (linesIndentedWithTabsCount < linesIndentedWithSpacesCount);\n }\n var tabSize = defaultTabSize;\n var tabSizeScore = (insertSpaces ? 0 : 0.1 * linesCount);\n // console.log(\"score threshold: \" + tabSizeScore);\n ALLOWED_TAB_SIZE_GUESSES.forEach(function (possibleTabSize) {\n var possibleTabSizeScore = spacesDiffCount[possibleTabSize];\n if (possibleTabSizeScore > tabSizeScore) {\n tabSizeScore = possibleTabSizeScore;\n tabSize = possibleTabSize;\n }\n });\n // Let a tabSize of 2 win even if it is not the maximum\n // (only in case 4 was guessed)\n if (tabSize === 4 && spacesDiffCount[4] > 0 && spacesDiffCount[2] > 0 && spacesDiffCount[2] >= spacesDiffCount[4] / 2) {\n tabSize = 2;\n }\n // console.log('--------------------------');\n // console.log('linesIndentedWithTabsCount: ' + linesIndentedWithTabsCount + ', linesIndentedWithSpacesCount: ' + linesIndentedWithSpacesCount);\n // console.log('spacesDiffCount: ' + spacesDiffCount);\n // console.log('tabSize: ' + tabSize + ', tabSizeScore: ' + tabSizeScore);\n return {\n insertSpaces: insertSpaces,\n tabSize: tabSize\n };\n}\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nexport function getNodeColor(node) {\n return ((node.metadata & 1 /* ColorMask */) >>> 0 /* ColorOffset */);\n}\nfunction setNodeColor(node, color) {\n node.metadata = ((node.metadata & 254 /* ColorMaskInverse */) | (color << 0 /* ColorOffset */));\n}\nfunction getNodeIsVisited(node) {\n return ((node.metadata & 2 /* IsVisitedMask */) >>> 1 /* IsVisitedOffset */) === 1;\n}\nfunction setNodeIsVisited(node, value) {\n node.metadata = ((node.metadata & 253 /* IsVisitedMaskInverse */) | ((value ? 1 : 0) << 1 /* IsVisitedOffset */));\n}\nfunction getNodeIsForValidation(node) {\n return ((node.metadata & 4 /* IsForValidationMask */) >>> 2 /* IsForValidationOffset */) === 1;\n}\nfunction setNodeIsForValidation(node, value) {\n node.metadata = ((node.metadata & 251 /* IsForValidationMaskInverse */) | ((value ? 1 : 0) << 2 /* IsForValidationOffset */));\n}\nexport function getNodeIsInOverviewRuler(node) {\n return ((node.metadata & 8 /* IsInOverviewRulerMask */) >>> 3 /* IsInOverviewRulerOffset */) === 1;\n}\nfunction setNodeIsInOverviewRuler(node, value) {\n node.metadata = ((node.metadata & 247 /* IsInOverviewRulerMaskInverse */) | ((value ? 1 : 0) << 3 /* IsInOverviewRulerOffset */));\n}\nfunction getNodeStickiness(node) {\n return ((node.metadata & 48 /* StickinessMask */) >>> 4 /* StickinessOffset */);\n}\nfunction _setNodeStickiness(node, stickiness) {\n node.metadata = ((node.metadata & 207 /* StickinessMaskInverse */) | (stickiness << 4 /* StickinessOffset */));\n}\nfunction getCollapseOnReplaceEdit(node) {\n return ((node.metadata & 64 /* CollapseOnReplaceEditMask */) >>> 6 /* CollapseOnReplaceEditOffset */) === 1;\n}\nfunction setCollapseOnReplaceEdit(node, value) {\n node.metadata = ((node.metadata & 191 /* CollapseOnReplaceEditMaskInverse */) | ((value ? 1 : 0) << 6 /* CollapseOnReplaceEditOffset */));\n}\nvar IntervalNode = /** @class */ (function () {\n function IntervalNode(id, start, end) {\n this.metadata = 0;\n this.parent = this;\n this.left = this;\n this.right = this;\n setNodeColor(this, 1 /* Red */);\n this.start = start;\n this.end = end;\n // FORCE_OVERFLOWING_TEST: this.delta = start;\n this.delta = 0;\n this.maxEnd = end;\n this.id = id;\n this.ownerId = 0;\n this.options = null;\n setNodeIsForValidation(this, false);\n _setNodeStickiness(this, 1 /* NeverGrowsWhenTypingAtEdges */);\n setNodeIsInOverviewRuler(this, false);\n setCollapseOnReplaceEdit(this, false);\n this.cachedVersionId = 0;\n this.cachedAbsoluteStart = start;\n this.cachedAbsoluteEnd = end;\n this.range = null;\n setNodeIsVisited(this, false);\n }\n IntervalNode.prototype.reset = function (versionId, start, end, range) {\n this.start = start;\n this.end = end;\n this.maxEnd = end;\n this.cachedVersionId = versionId;\n this.cachedAbsoluteStart = start;\n this.cachedAbsoluteEnd = end;\n this.range = range;\n };\n IntervalNode.prototype.setOptions = function (options) {\n this.options = options;\n var className = this.options.className;\n setNodeIsForValidation(this, (className === \"squiggly-error\" /* EditorErrorDecoration */\n || className === \"squiggly-warning\" /* EditorWarningDecoration */\n || className === \"squiggly-info\" /* EditorInfoDecoration */));\n _setNodeStickiness(this, this.options.stickiness);\n setNodeIsInOverviewRuler(this, (this.options.overviewRuler && this.options.overviewRuler.color) ? true : false);\n setCollapseOnReplaceEdit(this, this.options.collapseOnReplaceEdit);\n };\n IntervalNode.prototype.setCachedOffsets = function (absoluteStart, absoluteEnd, cachedVersionId) {\n if (this.cachedVersionId !== cachedVersionId) {\n this.range = null;\n }\n this.cachedVersionId = cachedVersionId;\n this.cachedAbsoluteStart = absoluteStart;\n this.cachedAbsoluteEnd = absoluteEnd;\n };\n IntervalNode.prototype.detach = function () {\n this.parent = null;\n this.left = null;\n this.right = null;\n };\n return IntervalNode;\n}());\nexport { IntervalNode };\nexport var SENTINEL = new IntervalNode(null, 0, 0);\nSENTINEL.parent = SENTINEL;\nSENTINEL.left = SENTINEL;\nSENTINEL.right = SENTINEL;\nsetNodeColor(SENTINEL, 0 /* Black */);\nvar IntervalTree = /** @class */ (function () {\n function IntervalTree() {\n this.root = SENTINEL;\n this.requestNormalizeDelta = false;\n }\n IntervalTree.prototype.intervalSearch = function (start, end, filterOwnerId, filterOutValidation, cachedVersionId) {\n if (this.root === SENTINEL) {\n return [];\n }\n return intervalSearch(this, start, end, filterOwnerId, filterOutValidation, cachedVersionId);\n };\n IntervalTree.prototype.search = function (filterOwnerId, filterOutValidation, cachedVersionId) {\n if (this.root === SENTINEL) {\n return [];\n }\n return search(this, filterOwnerId, filterOutValidation, cachedVersionId);\n };\n /**\n * Will not set `cachedAbsoluteStart` nor `cachedAbsoluteEnd` on the returned nodes!\n */\n IntervalTree.prototype.collectNodesFromOwner = function (ownerId) {\n return collectNodesFromOwner(this, ownerId);\n };\n /**\n * Will not set `cachedAbsoluteStart` nor `cachedAbsoluteEnd` on the returned nodes!\n */\n IntervalTree.prototype.collectNodesPostOrder = function () {\n return collectNodesPostOrder(this);\n };\n IntervalTree.prototype.insert = function (node) {\n rbTreeInsert(this, node);\n this._normalizeDeltaIfNecessary();\n };\n IntervalTree.prototype.delete = function (node) {\n rbTreeDelete(this, node);\n this._normalizeDeltaIfNecessary();\n };\n IntervalTree.prototype.resolveNode = function (node, cachedVersionId) {\n var initialNode = node;\n var delta = 0;\n while (node !== this.root) {\n if (node === node.parent.right) {\n delta += node.parent.delta;\n }\n node = node.parent;\n }\n var nodeStart = initialNode.start + delta;\n var nodeEnd = initialNode.end + delta;\n initialNode.setCachedOffsets(nodeStart, nodeEnd, cachedVersionId);\n };\n IntervalTree.prototype.acceptReplace = function (offset, length, textLength, forceMoveMarkers) {\n // Our strategy is to remove all directly impacted nodes, and then add them back to the tree.\n // (1) collect all nodes that are intersecting this edit as nodes of interest\n var nodesOfInterest = searchForEditing(this, offset, offset + length);\n // (2) remove all nodes that are intersecting this edit\n for (var i = 0, len = nodesOfInterest.length; i < len; i++) {\n var node = nodesOfInterest[i];\n rbTreeDelete(this, node);\n }\n this._normalizeDeltaIfNecessary();\n // (3) edit all tree nodes except the nodes of interest\n noOverlapReplace(this, offset, offset + length, textLength);\n this._normalizeDeltaIfNecessary();\n // (4) edit the nodes of interest and insert them back in the tree\n for (var i = 0, len = nodesOfInterest.length; i < len; i++) {\n var node = nodesOfInterest[i];\n node.start = node.cachedAbsoluteStart;\n node.end = node.cachedAbsoluteEnd;\n nodeAcceptEdit(node, offset, (offset + length), textLength, forceMoveMarkers);\n node.maxEnd = node.end;\n rbTreeInsert(this, node);\n }\n this._normalizeDeltaIfNecessary();\n };\n IntervalTree.prototype._normalizeDeltaIfNecessary = function () {\n if (!this.requestNormalizeDelta) {\n return;\n }\n this.requestNormalizeDelta = false;\n normalizeDelta(this);\n };\n return IntervalTree;\n}());\nexport { IntervalTree };\n//#region Delta Normalization\nfunction normalizeDelta(T) {\n var node = T.root;\n var delta = 0;\n while (node !== SENTINEL) {\n if (node.left !== SENTINEL && !getNodeIsVisited(node.left)) {\n // go left\n node = node.left;\n continue;\n }\n if (node.right !== SENTINEL && !getNodeIsVisited(node.right)) {\n // go right\n delta += node.delta;\n node = node.right;\n continue;\n }\n // handle current node\n node.start = delta + node.start;\n node.end = delta + node.end;\n node.delta = 0;\n recomputeMaxEnd(node);\n setNodeIsVisited(node, true);\n // going up from this node\n setNodeIsVisited(node.left, false);\n setNodeIsVisited(node.right, false);\n if (node === node.parent.right) {\n delta -= node.parent.delta;\n }\n node = node.parent;\n }\n setNodeIsVisited(T.root, false);\n}\nfunction adjustMarkerBeforeColumn(markerOffset, markerStickToPreviousCharacter, checkOffset, moveSemantics) {\n if (markerOffset < checkOffset) {\n return true;\n }\n if (markerOffset > checkOffset) {\n return false;\n }\n if (moveSemantics === 1 /* ForceMove */) {\n return false;\n }\n if (moveSemantics === 2 /* ForceStay */) {\n return true;\n }\n return markerStickToPreviousCharacter;\n}\n/**\n * This is a lot more complicated than strictly necessary to maintain the same behaviour\n * as when decorations were implemented using two markers.\n */\nexport function nodeAcceptEdit(node, start, end, textLength, forceMoveMarkers) {\n var nodeStickiness = getNodeStickiness(node);\n var startStickToPreviousCharacter = (nodeStickiness === 0 /* AlwaysGrowsWhenTypingAtEdges */\n || nodeStickiness === 2 /* GrowsOnlyWhenTypingBefore */);\n var endStickToPreviousCharacter = (nodeStickiness === 1 /* NeverGrowsWhenTypingAtEdges */\n || nodeStickiness === 2 /* GrowsOnlyWhenTypingBefore */);\n var deletingCnt = (end - start);\n var insertingCnt = textLength;\n var commonLength = Math.min(deletingCnt, insertingCnt);\n var nodeStart = node.start;\n var startDone = false;\n var nodeEnd = node.end;\n var endDone = false;\n if (start <= nodeStart && nodeEnd <= end && getCollapseOnReplaceEdit(node)) {\n // This edit encompasses the entire decoration range\n // and the decoration has asked to become collapsed\n node.start = start;\n startDone = true;\n node.end = start;\n endDone = true;\n }\n {\n var moveSemantics = forceMoveMarkers ? 1 /* ForceMove */ : (deletingCnt > 0 ? 2 /* ForceStay */ : 0 /* MarkerDefined */);\n if (!startDone && adjustMarkerBeforeColumn(nodeStart, startStickToPreviousCharacter, start, moveSemantics)) {\n startDone = true;\n }\n if (!endDone && adjustMarkerBeforeColumn(nodeEnd, endStickToPreviousCharacter, start, moveSemantics)) {\n endDone = true;\n }\n }\n if (commonLength > 0 && !forceMoveMarkers) {\n var moveSemantics = (deletingCnt > insertingCnt ? 2 /* ForceStay */ : 0 /* MarkerDefined */);\n if (!startDone && adjustMarkerBeforeColumn(nodeStart, startStickToPreviousCharacter, start + commonLength, moveSemantics)) {\n startDone = true;\n }\n if (!endDone && adjustMarkerBeforeColumn(nodeEnd, endStickToPreviousCharacter, start + commonLength, moveSemantics)) {\n endDone = true;\n }\n }\n {\n var moveSemantics = forceMoveMarkers ? 1 /* ForceMove */ : 0 /* MarkerDefined */;\n if (!startDone && adjustMarkerBeforeColumn(nodeStart, startStickToPreviousCharacter, end, moveSemantics)) {\n node.start = start + insertingCnt;\n startDone = true;\n }\n if (!endDone && adjustMarkerBeforeColumn(nodeEnd, endStickToPreviousCharacter, end, moveSemantics)) {\n node.end = start + insertingCnt;\n endDone = true;\n }\n }\n // Finish\n var deltaColumn = (insertingCnt - deletingCnt);\n if (!startDone) {\n node.start = Math.max(0, nodeStart + deltaColumn);\n }\n if (!endDone) {\n node.end = Math.max(0, nodeEnd + deltaColumn);\n }\n if (node.start > node.end) {\n node.end = node.start;\n }\n}\nfunction searchForEditing(T, start, end) {\n // https://en.wikipedia.org/wiki/Interval_tree#Augmented_tree\n // Now, it is known that two intervals A and B overlap only when both\n // A.low <= B.high and A.high >= B.low. When searching the trees for\n // nodes overlapping with a given interval, you can immediately skip:\n // a) all nodes to the right of nodes whose low value is past the end of the given interval.\n // b) all nodes that have their maximum 'high' value below the start of the given interval.\n var node = T.root;\n var delta = 0;\n var nodeMaxEnd = 0;\n var nodeStart = 0;\n var nodeEnd = 0;\n var result = [];\n var resultLen = 0;\n while (node !== SENTINEL) {\n if (getNodeIsVisited(node)) {\n // going up from this node\n setNodeIsVisited(node.left, false);\n setNodeIsVisited(node.right, false);\n if (node === node.parent.right) {\n delta -= node.parent.delta;\n }\n node = node.parent;\n continue;\n }\n if (!getNodeIsVisited(node.left)) {\n // first time seeing this node\n nodeMaxEnd = delta + node.maxEnd;\n if (nodeMaxEnd < start) {\n // cover case b) from above\n // there is no need to search this node or its children\n setNodeIsVisited(node, true);\n continue;\n }\n if (node.left !== SENTINEL) {\n // go left\n node = node.left;\n continue;\n }\n }\n // handle current node\n nodeStart = delta + node.start;\n if (nodeStart > end) {\n // cover case a) from above\n // there is no need to search this node or its right subtree\n setNodeIsVisited(node, true);\n continue;\n }\n nodeEnd = delta + node.end;\n if (nodeEnd >= start) {\n node.setCachedOffsets(nodeStart, nodeEnd, 0);\n result[resultLen++] = node;\n }\n setNodeIsVisited(node, true);\n if (node.right !== SENTINEL && !getNodeIsVisited(node.right)) {\n // go right\n delta += node.delta;\n node = node.right;\n continue;\n }\n }\n setNodeIsVisited(T.root, false);\n return result;\n}\nfunction noOverlapReplace(T, start, end, textLength) {\n // https://en.wikipedia.org/wiki/Interval_tree#Augmented_tree\n // Now, it is known that two intervals A and B overlap only when both\n // A.low <= B.high and A.high >= B.low. When searching the trees for\n // nodes overlapping with a given interval, you can immediately skip:\n // a) all nodes to the right of nodes whose low value is past the end of the given interval.\n // b) all nodes that have their maximum 'high' value below the start of the given interval.\n var node = T.root;\n var delta = 0;\n var nodeMaxEnd = 0;\n var nodeStart = 0;\n var editDelta = (textLength - (end - start));\n while (node !== SENTINEL) {\n if (getNodeIsVisited(node)) {\n // going up from this node\n setNodeIsVisited(node.left, false);\n setNodeIsVisited(node.right, false);\n if (node === node.parent.right) {\n delta -= node.parent.delta;\n }\n recomputeMaxEnd(node);\n node = node.parent;\n continue;\n }\n if (!getNodeIsVisited(node.left)) {\n // first time seeing this node\n nodeMaxEnd = delta + node.maxEnd;\n if (nodeMaxEnd < start) {\n // cover case b) from above\n // there is no need to search this node or its children\n setNodeIsVisited(node, true);\n continue;\n }\n if (node.left !== SENTINEL) {\n // go left\n node = node.left;\n continue;\n }\n }\n // handle current node\n nodeStart = delta + node.start;\n if (nodeStart > end) {\n node.start += editDelta;\n node.end += editDelta;\n node.delta += editDelta;\n if (node.delta < -1073741824 /* MIN_SAFE_DELTA */ || node.delta > 1073741824 /* MAX_SAFE_DELTA */) {\n T.requestNormalizeDelta = true;\n }\n // cover case a) from above\n // there is no need to search this node or its right subtree\n setNodeIsVisited(node, true);\n continue;\n }\n setNodeIsVisited(node, true);\n if (node.right !== SENTINEL && !getNodeIsVisited(node.right)) {\n // go right\n delta += node.delta;\n node = node.right;\n continue;\n }\n }\n setNodeIsVisited(T.root, false);\n}\n//#endregion\n//#region Searching\nfunction collectNodesFromOwner(T, ownerId) {\n var node = T.root;\n var result = [];\n var resultLen = 0;\n while (node !== SENTINEL) {\n if (getNodeIsVisited(node)) {\n // going up from this node\n setNodeIsVisited(node.left, false);\n setNodeIsVisited(node.right, false);\n node = node.parent;\n continue;\n }\n if (node.left !== SENTINEL && !getNodeIsVisited(node.left)) {\n // go left\n node = node.left;\n continue;\n }\n // handle current node\n if (node.ownerId === ownerId) {\n result[resultLen++] = node;\n }\n setNodeIsVisited(node, true);\n if (node.right !== SENTINEL && !getNodeIsVisited(node.right)) {\n // go right\n node = node.right;\n continue;\n }\n }\n setNodeIsVisited(T.root, false);\n return result;\n}\nfunction collectNodesPostOrder(T) {\n var node = T.root;\n var result = [];\n var resultLen = 0;\n while (node !== SENTINEL) {\n if (getNodeIsVisited(node)) {\n // going up from this node\n setNodeIsVisited(node.left, false);\n setNodeIsVisited(node.right, false);\n node = node.parent;\n continue;\n }\n if (node.left !== SENTINEL && !getNodeIsVisited(node.left)) {\n // go left\n node = node.left;\n continue;\n }\n if (node.right !== SENTINEL && !getNodeIsVisited(node.right)) {\n // go right\n node = node.right;\n continue;\n }\n // handle current node\n result[resultLen++] = node;\n setNodeIsVisited(node, true);\n }\n setNodeIsVisited(T.root, false);\n return result;\n}\nfunction search(T, filterOwnerId, filterOutValidation, cachedVersionId) {\n var node = T.root;\n var delta = 0;\n var nodeStart = 0;\n var nodeEnd = 0;\n var result = [];\n var resultLen = 0;\n while (node !== SENTINEL) {\n if (getNodeIsVisited(node)) {\n // going up from this node\n setNodeIsVisited(node.left, false);\n setNodeIsVisited(node.right, false);\n if (node === node.parent.right) {\n delta -= node.parent.delta;\n }\n node = node.parent;\n continue;\n }\n if (node.left !== SENTINEL && !getNodeIsVisited(node.left)) {\n // go left\n node = node.left;\n continue;\n }\n // handle current node\n nodeStart = delta + node.start;\n nodeEnd = delta + node.end;\n node.setCachedOffsets(nodeStart, nodeEnd, cachedVersionId);\n var include = true;\n if (filterOwnerId && node.ownerId && node.ownerId !== filterOwnerId) {\n include = false;\n }\n if (filterOutValidation && getNodeIsForValidation(node)) {\n include = false;\n }\n if (include) {\n result[resultLen++] = node;\n }\n setNodeIsVisited(node, true);\n if (node.right !== SENTINEL && !getNodeIsVisited(node.right)) {\n // go right\n delta += node.delta;\n node = node.right;\n continue;\n }\n }\n setNodeIsVisited(T.root, false);\n return result;\n}\nfunction intervalSearch(T, intervalStart, intervalEnd, filterOwnerId, filterOutValidation, cachedVersionId) {\n // https://en.wikipedia.org/wiki/Interval_tree#Augmented_tree\n // Now, it is known that two intervals A and B overlap only when both\n // A.low <= B.high and A.high >= B.low. When searching the trees for\n // nodes overlapping with a given interval, you can immediately skip:\n // a) all nodes to the right of nodes whose low value is past the end of the given interval.\n // b) all nodes that have their maximum 'high' value below the start of the given interval.\n var node = T.root;\n var delta = 0;\n var nodeMaxEnd = 0;\n var nodeStart = 0;\n var nodeEnd = 0;\n var result = [];\n var resultLen = 0;\n while (node !== SENTINEL) {\n if (getNodeIsVisited(node)) {\n // going up from this node\n setNodeIsVisited(node.left, false);\n setNodeIsVisited(node.right, false);\n if (node === node.parent.right) {\n delta -= node.parent.delta;\n }\n node = node.parent;\n continue;\n }\n if (!getNodeIsVisited(node.left)) {\n // first time seeing this node\n nodeMaxEnd = delta + node.maxEnd;\n if (nodeMaxEnd < intervalStart) {\n // cover case b) from above\n // there is no need to search this node or its children\n setNodeIsVisited(node, true);\n continue;\n }\n if (node.left !== SENTINEL) {\n // go left\n node = node.left;\n continue;\n }\n }\n // handle current node\n nodeStart = delta + node.start;\n if (nodeStart > intervalEnd) {\n // cover case a) from above\n // there is no need to search this node or its right subtree\n setNodeIsVisited(node, true);\n continue;\n }\n nodeEnd = delta + node.end;\n if (nodeEnd >= intervalStart) {\n // There is overlap\n node.setCachedOffsets(nodeStart, nodeEnd, cachedVersionId);\n var include = true;\n if (filterOwnerId && node.ownerId && node.ownerId !== filterOwnerId) {\n include = false;\n }\n if (filterOutValidation && getNodeIsForValidation(node)) {\n include = false;\n }\n if (include) {\n result[resultLen++] = node;\n }\n }\n setNodeIsVisited(node, true);\n if (node.right !== SENTINEL && !getNodeIsVisited(node.right)) {\n // go right\n delta += node.delta;\n node = node.right;\n continue;\n }\n }\n setNodeIsVisited(T.root, false);\n return result;\n}\n//#endregion\n//#region Insertion\nfunction rbTreeInsert(T, newNode) {\n if (T.root === SENTINEL) {\n newNode.parent = SENTINEL;\n newNode.left = SENTINEL;\n newNode.right = SENTINEL;\n setNodeColor(newNode, 0 /* Black */);\n T.root = newNode;\n return T.root;\n }\n treeInsert(T, newNode);\n recomputeMaxEndWalkToRoot(newNode.parent);\n // repair tree\n var x = newNode;\n while (x !== T.root && getNodeColor(x.parent) === 1 /* Red */) {\n if (x.parent === x.parent.parent.left) {\n var y = x.parent.parent.right;\n if (getNodeColor(y) === 1 /* Red */) {\n setNodeColor(x.parent, 0 /* Black */);\n setNodeColor(y, 0 /* Black */);\n setNodeColor(x.parent.parent, 1 /* Red */);\n x = x.parent.parent;\n }\n else {\n if (x === x.parent.right) {\n x = x.parent;\n leftRotate(T, x);\n }\n setNodeColor(x.parent, 0 /* Black */);\n setNodeColor(x.parent.parent, 1 /* Red */);\n rightRotate(T, x.parent.parent);\n }\n }\n else {\n var y = x.parent.parent.left;\n if (getNodeColor(y) === 1 /* Red */) {\n setNodeColor(x.parent, 0 /* Black */);\n setNodeColor(y, 0 /* Black */);\n setNodeColor(x.parent.parent, 1 /* Red */);\n x = x.parent.parent;\n }\n else {\n if (x === x.parent.left) {\n x = x.parent;\n rightRotate(T, x);\n }\n setNodeColor(x.parent, 0 /* Black */);\n setNodeColor(x.parent.parent, 1 /* Red */);\n leftRotate(T, x.parent.parent);\n }\n }\n }\n setNodeColor(T.root, 0 /* Black */);\n return newNode;\n}\nfunction treeInsert(T, z) {\n var delta = 0;\n var x = T.root;\n var zAbsoluteStart = z.start;\n var zAbsoluteEnd = z.end;\n while (true) {\n var cmp = intervalCompare(zAbsoluteStart, zAbsoluteEnd, x.start + delta, x.end + delta);\n if (cmp < 0) {\n // this node should be inserted to the left\n // => it is not affected by the node's delta\n if (x.left === SENTINEL) {\n z.start -= delta;\n z.end -= delta;\n z.maxEnd -= delta;\n x.left = z;\n break;\n }\n else {\n x = x.left;\n }\n }\n else {\n // this node should be inserted to the right\n // => it is not affected by the node's delta\n if (x.right === SENTINEL) {\n z.start -= (delta + x.delta);\n z.end -= (delta + x.delta);\n z.maxEnd -= (delta + x.delta);\n x.right = z;\n break;\n }\n else {\n delta += x.delta;\n x = x.right;\n }\n }\n }\n z.parent = x;\n z.left = SENTINEL;\n z.right = SENTINEL;\n setNodeColor(z, 1 /* Red */);\n}\n//#endregion\n//#region Deletion\nfunction rbTreeDelete(T, z) {\n var x;\n var y;\n // RB-DELETE except we don't swap z and y in case c)\n // i.e. we always delete what's pointed at by z.\n if (z.left === SENTINEL) {\n x = z.right;\n y = z;\n // x's delta is no longer influenced by z's delta\n x.delta += z.delta;\n if (x.delta < -1073741824 /* MIN_SAFE_DELTA */ || x.delta > 1073741824 /* MAX_SAFE_DELTA */) {\n T.requestNormalizeDelta = true;\n }\n x.start += z.delta;\n x.end += z.delta;\n }\n else if (z.right === SENTINEL) {\n x = z.left;\n y = z;\n }\n else {\n y = leftest(z.right);\n x = y.right;\n // y's delta is no longer influenced by z's delta,\n // but we don't want to walk the entire right-hand-side subtree of x.\n // we therefore maintain z's delta in y, and adjust only x\n x.start += y.delta;\n x.end += y.delta;\n x.delta += y.delta;\n if (x.delta < -1073741824 /* MIN_SAFE_DELTA */ || x.delta > 1073741824 /* MAX_SAFE_DELTA */) {\n T.requestNormalizeDelta = true;\n }\n y.start += z.delta;\n y.end += z.delta;\n y.delta = z.delta;\n if (y.delta < -1073741824 /* MIN_SAFE_DELTA */ || y.delta > 1073741824 /* MAX_SAFE_DELTA */) {\n T.requestNormalizeDelta = true;\n }\n }\n if (y === T.root) {\n T.root = x;\n setNodeColor(x, 0 /* Black */);\n z.detach();\n resetSentinel();\n recomputeMaxEnd(x);\n T.root.parent = SENTINEL;\n return;\n }\n var yWasRed = (getNodeColor(y) === 1 /* Red */);\n if (y === y.parent.left) {\n y.parent.left = x;\n }\n else {\n y.parent.right = x;\n }\n if (y === z) {\n x.parent = y.parent;\n }\n else {\n if (y.parent === z) {\n x.parent = y;\n }\n else {\n x.parent = y.parent;\n }\n y.left = z.left;\n y.right = z.right;\n y.parent = z.parent;\n setNodeColor(y, getNodeColor(z));\n if (z === T.root) {\n T.root = y;\n }\n else {\n if (z === z.parent.left) {\n z.parent.left = y;\n }\n else {\n z.parent.right = y;\n }\n }\n if (y.left !== SENTINEL) {\n y.left.parent = y;\n }\n if (y.right !== SENTINEL) {\n y.right.parent = y;\n }\n }\n z.detach();\n if (yWasRed) {\n recomputeMaxEndWalkToRoot(x.parent);\n if (y !== z) {\n recomputeMaxEndWalkToRoot(y);\n recomputeMaxEndWalkToRoot(y.parent);\n }\n resetSentinel();\n return;\n }\n recomputeMaxEndWalkToRoot(x);\n recomputeMaxEndWalkToRoot(x.parent);\n if (y !== z) {\n recomputeMaxEndWalkToRoot(y);\n recomputeMaxEndWalkToRoot(y.parent);\n }\n // RB-DELETE-FIXUP\n var w;\n while (x !== T.root && getNodeColor(x) === 0 /* Black */) {\n if (x === x.parent.left) {\n w = x.parent.right;\n if (getNodeColor(w) === 1 /* Red */) {\n setNodeColor(w, 0 /* Black */);\n setNodeColor(x.parent, 1 /* Red */);\n leftRotate(T, x.parent);\n w = x.parent.right;\n }\n if (getNodeColor(w.left) === 0 /* Black */ && getNodeColor(w.right) === 0 /* Black */) {\n setNodeColor(w, 1 /* Red */);\n x = x.parent;\n }\n else {\n if (getNodeColor(w.right) === 0 /* Black */) {\n setNodeColor(w.left, 0 /* Black */);\n setNodeColor(w, 1 /* Red */);\n rightRotate(T, w);\n w = x.parent.right;\n }\n setNodeColor(w, getNodeColor(x.parent));\n setNodeColor(x.parent, 0 /* Black */);\n setNodeColor(w.right, 0 /* Black */);\n leftRotate(T, x.parent);\n x = T.root;\n }\n }\n else {\n w = x.parent.left;\n if (getNodeColor(w) === 1 /* Red */) {\n setNodeColor(w, 0 /* Black */);\n setNodeColor(x.parent, 1 /* Red */);\n rightRotate(T, x.parent);\n w = x.parent.left;\n }\n if (getNodeColor(w.left) === 0 /* Black */ && getNodeColor(w.right) === 0 /* Black */) {\n setNodeColor(w, 1 /* Red */);\n x = x.parent;\n }\n else {\n if (getNodeColor(w.left) === 0 /* Black */) {\n setNodeColor(w.right, 0 /* Black */);\n setNodeColor(w, 1 /* Red */);\n leftRotate(T, w);\n w = x.parent.left;\n }\n setNodeColor(w, getNodeColor(x.parent));\n setNodeColor(x.parent, 0 /* Black */);\n setNodeColor(w.left, 0 /* Black */);\n rightRotate(T, x.parent);\n x = T.root;\n }\n }\n }\n setNodeColor(x, 0 /* Black */);\n resetSentinel();\n}\nfunction leftest(node) {\n while (node.left !== SENTINEL) {\n node = node.left;\n }\n return node;\n}\nfunction resetSentinel() {\n SENTINEL.parent = SENTINEL;\n SENTINEL.delta = 0; // optional\n SENTINEL.start = 0; // optional\n SENTINEL.end = 0; // optional\n}\n//#endregion\n//#region Rotations\nfunction leftRotate(T, x) {\n var y = x.right; // set y.\n y.delta += x.delta; // y's delta is no longer influenced by x's delta\n if (y.delta < -1073741824 /* MIN_SAFE_DELTA */ || y.delta > 1073741824 /* MAX_SAFE_DELTA */) {\n T.requestNormalizeDelta = true;\n }\n y.start += x.delta;\n y.end += x.delta;\n x.right = y.left; // turn y's left subtree into x's right subtree.\n if (y.left !== SENTINEL) {\n y.left.parent = x;\n }\n y.parent = x.parent; // link x's parent to y.\n if (x.parent === SENTINEL) {\n T.root = y;\n }\n else if (x === x.parent.left) {\n x.parent.left = y;\n }\n else {\n x.parent.right = y;\n }\n y.left = x; // put x on y's left.\n x.parent = y;\n recomputeMaxEnd(x);\n recomputeMaxEnd(y);\n}\nfunction rightRotate(T, y) {\n var x = y.left;\n y.delta -= x.delta;\n if (y.delta < -1073741824 /* MIN_SAFE_DELTA */ || y.delta > 1073741824 /* MAX_SAFE_DELTA */) {\n T.requestNormalizeDelta = true;\n }\n y.start -= x.delta;\n y.end -= x.delta;\n y.left = x.right;\n if (x.right !== SENTINEL) {\n x.right.parent = y;\n }\n x.parent = y.parent;\n if (y.parent === SENTINEL) {\n T.root = x;\n }\n else if (y === y.parent.right) {\n y.parent.right = x;\n }\n else {\n y.parent.left = x;\n }\n x.right = y;\n y.parent = x;\n recomputeMaxEnd(y);\n recomputeMaxEnd(x);\n}\n//#endregion\n//#region max end computation\nfunction computeMaxEnd(node) {\n var maxEnd = node.end;\n if (node.left !== SENTINEL) {\n var leftMaxEnd = node.left.maxEnd;\n if (leftMaxEnd > maxEnd) {\n maxEnd = leftMaxEnd;\n }\n }\n if (node.right !== SENTINEL) {\n var rightMaxEnd = node.right.maxEnd + node.delta;\n if (rightMaxEnd > maxEnd) {\n maxEnd = rightMaxEnd;\n }\n }\n return maxEnd;\n}\nexport function recomputeMaxEnd(node) {\n node.maxEnd = computeMaxEnd(node);\n}\nfunction recomputeMaxEndWalkToRoot(node) {\n while (node !== SENTINEL) {\n var maxEnd = computeMaxEnd(node);\n if (node.maxEnd === maxEnd) {\n // no need to go further\n return;\n }\n node.maxEnd = maxEnd;\n node = node.parent;\n }\n}\n//#endregion\n//#region utils\nexport function intervalCompare(aStart, aEnd, bStart, bEnd) {\n if (aStart === bStart) {\n return aEnd - bEnd;\n }\n return aStart - bStart;\n}\n//#endregion\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nvar TreeNode = /** @class */ (function () {\n function TreeNode(piece, color) {\n this.piece = piece;\n this.color = color;\n this.size_left = 0;\n this.lf_left = 0;\n this.parent = this;\n this.left = this;\n this.right = this;\n }\n TreeNode.prototype.next = function () {\n if (this.right !== SENTINEL) {\n return leftest(this.right);\n }\n var node = this;\n while (node.parent !== SENTINEL) {\n if (node.parent.left === node) {\n break;\n }\n node = node.parent;\n }\n if (node.parent === SENTINEL) {\n return SENTINEL;\n }\n else {\n return node.parent;\n }\n };\n TreeNode.prototype.prev = function () {\n if (this.left !== SENTINEL) {\n return righttest(this.left);\n }\n var node = this;\n while (node.parent !== SENTINEL) {\n if (node.parent.right === node) {\n break;\n }\n node = node.parent;\n }\n if (node.parent === SENTINEL) {\n return SENTINEL;\n }\n else {\n return node.parent;\n }\n };\n TreeNode.prototype.detach = function () {\n this.parent = null;\n this.left = null;\n this.right = null;\n };\n return TreeNode;\n}());\nexport { TreeNode };\nexport var SENTINEL = new TreeNode(null, 0 /* Black */);\nSENTINEL.parent = SENTINEL;\nSENTINEL.left = SENTINEL;\nSENTINEL.right = SENTINEL;\nSENTINEL.color = 0 /* Black */;\nexport function leftest(node) {\n while (node.left !== SENTINEL) {\n node = node.left;\n }\n return node;\n}\nexport function righttest(node) {\n while (node.right !== SENTINEL) {\n node = node.right;\n }\n return node;\n}\nexport function calculateSize(node) {\n if (node === SENTINEL) {\n return 0;\n }\n return node.size_left + node.piece.length + calculateSize(node.right);\n}\nexport function calculateLF(node) {\n if (node === SENTINEL) {\n return 0;\n }\n return node.lf_left + node.piece.lineFeedCnt + calculateLF(node.right);\n}\nexport function resetSentinel() {\n SENTINEL.parent = SENTINEL;\n}\nexport function leftRotate(tree, x) {\n var y = x.right;\n // fix size_left\n y.size_left += x.size_left + (x.piece ? x.piece.length : 0);\n y.lf_left += x.lf_left + (x.piece ? x.piece.lineFeedCnt : 0);\n x.right = y.left;\n if (y.left !== SENTINEL) {\n y.left.parent = x;\n }\n y.parent = x.parent;\n if (x.parent === SENTINEL) {\n tree.root = y;\n }\n else if (x.parent.left === x) {\n x.parent.left = y;\n }\n else {\n x.parent.right = y;\n }\n y.left = x;\n x.parent = y;\n}\nexport function rightRotate(tree, y) {\n var x = y.left;\n y.left = x.right;\n if (x.right !== SENTINEL) {\n x.right.parent = y;\n }\n x.parent = y.parent;\n // fix size_left\n y.size_left -= x.size_left + (x.piece ? x.piece.length : 0);\n y.lf_left -= x.lf_left + (x.piece ? x.piece.lineFeedCnt : 0);\n if (y.parent === SENTINEL) {\n tree.root = x;\n }\n else if (y === y.parent.right) {\n y.parent.right = x;\n }\n else {\n y.parent.left = x;\n }\n x.right = y;\n y.parent = x;\n}\nexport function rbDelete(tree, z) {\n var x;\n var y;\n if (z.left === SENTINEL) {\n y = z;\n x = y.right;\n }\n else if (z.right === SENTINEL) {\n y = z;\n x = y.left;\n }\n else {\n y = leftest(z.right);\n x = y.right;\n }\n if (y === tree.root) {\n tree.root = x;\n // if x is null, we are removing the only node\n x.color = 0 /* Black */;\n z.detach();\n resetSentinel();\n tree.root.parent = SENTINEL;\n return;\n }\n var yWasRed = (y.color === 1 /* Red */);\n if (y === y.parent.left) {\n y.parent.left = x;\n }\n else {\n y.parent.right = x;\n }\n if (y === z) {\n x.parent = y.parent;\n recomputeTreeMetadata(tree, x);\n }\n else {\n if (y.parent === z) {\n x.parent = y;\n }\n else {\n x.parent = y.parent;\n }\n // as we make changes to x's hierarchy, update size_left of subtree first\n recomputeTreeMetadata(tree, x);\n y.left = z.left;\n y.right = z.right;\n y.parent = z.parent;\n y.color = z.color;\n if (z === tree.root) {\n tree.root = y;\n }\n else {\n if (z === z.parent.left) {\n z.parent.left = y;\n }\n else {\n z.parent.right = y;\n }\n }\n if (y.left !== SENTINEL) {\n y.left.parent = y;\n }\n if (y.right !== SENTINEL) {\n y.right.parent = y;\n }\n // update metadata\n // we replace z with y, so in this sub tree, the length change is z.item.length\n y.size_left = z.size_left;\n y.lf_left = z.lf_left;\n recomputeTreeMetadata(tree, y);\n }\n z.detach();\n if (x.parent.left === x) {\n var newSizeLeft = calculateSize(x);\n var newLFLeft = calculateLF(x);\n if (newSizeLeft !== x.parent.size_left || newLFLeft !== x.parent.lf_left) {\n var delta = newSizeLeft - x.parent.size_left;\n var lf_delta = newLFLeft - x.parent.lf_left;\n x.parent.size_left = newSizeLeft;\n x.parent.lf_left = newLFLeft;\n updateTreeMetadata(tree, x.parent, delta, lf_delta);\n }\n }\n recomputeTreeMetadata(tree, x.parent);\n if (yWasRed) {\n resetSentinel();\n return;\n }\n // RB-DELETE-FIXUP\n var w;\n while (x !== tree.root && x.color === 0 /* Black */) {\n if (x === x.parent.left) {\n w = x.parent.right;\n if (w.color === 1 /* Red */) {\n w.color = 0 /* Black */;\n x.parent.color = 1 /* Red */;\n leftRotate(tree, x.parent);\n w = x.parent.right;\n }\n if (w.left.color === 0 /* Black */ && w.right.color === 0 /* Black */) {\n w.color = 1 /* Red */;\n x = x.parent;\n }\n else {\n if (w.right.color === 0 /* Black */) {\n w.left.color = 0 /* Black */;\n w.color = 1 /* Red */;\n rightRotate(tree, w);\n w = x.parent.right;\n }\n w.color = x.parent.color;\n x.parent.color = 0 /* Black */;\n w.right.color = 0 /* Black */;\n leftRotate(tree, x.parent);\n x = tree.root;\n }\n }\n else {\n w = x.parent.left;\n if (w.color === 1 /* Red */) {\n w.color = 0 /* Black */;\n x.parent.color = 1 /* Red */;\n rightRotate(tree, x.parent);\n w = x.parent.left;\n }\n if (w.left.color === 0 /* Black */ && w.right.color === 0 /* Black */) {\n w.color = 1 /* Red */;\n x = x.parent;\n }\n else {\n if (w.left.color === 0 /* Black */) {\n w.right.color = 0 /* Black */;\n w.color = 1 /* Red */;\n leftRotate(tree, w);\n w = x.parent.left;\n }\n w.color = x.parent.color;\n x.parent.color = 0 /* Black */;\n w.left.color = 0 /* Black */;\n rightRotate(tree, x.parent);\n x = tree.root;\n }\n }\n }\n x.color = 0 /* Black */;\n resetSentinel();\n}\nexport function fixInsert(tree, x) {\n recomputeTreeMetadata(tree, x);\n while (x !== tree.root && x.parent.color === 1 /* Red */) {\n if (x.parent === x.parent.parent.left) {\n var y = x.parent.parent.right;\n if (y.color === 1 /* Red */) {\n x.parent.color = 0 /* Black */;\n y.color = 0 /* Black */;\n x.parent.parent.color = 1 /* Red */;\n x = x.parent.parent;\n }\n else {\n if (x === x.parent.right) {\n x = x.parent;\n leftRotate(tree, x);\n }\n x.parent.color = 0 /* Black */;\n x.parent.parent.color = 1 /* Red */;\n rightRotate(tree, x.parent.parent);\n }\n }\n else {\n var y = x.parent.parent.left;\n if (y.color === 1 /* Red */) {\n x.parent.color = 0 /* Black */;\n y.color = 0 /* Black */;\n x.parent.parent.color = 1 /* Red */;\n x = x.parent.parent;\n }\n else {\n if (x === x.parent.left) {\n x = x.parent;\n rightRotate(tree, x);\n }\n x.parent.color = 0 /* Black */;\n x.parent.parent.color = 1 /* Red */;\n leftRotate(tree, x.parent.parent);\n }\n }\n }\n tree.root.color = 0 /* Black */;\n}\nexport function updateTreeMetadata(tree, x, delta, lineFeedCntDelta) {\n // node length change or line feed count change\n while (x !== tree.root && x !== SENTINEL) {\n if (x.parent.left === x) {\n x.parent.size_left += delta;\n x.parent.lf_left += lineFeedCntDelta;\n }\n x = x.parent;\n }\n}\nexport function recomputeTreeMetadata(tree, x) {\n var delta = 0;\n var lf_delta = 0;\n if (x === tree.root) {\n return;\n }\n if (delta === 0) {\n // go upwards till the node whose left subtree is changed.\n while (x !== tree.root && x === x.parent.right) {\n x = x.parent;\n }\n if (x === tree.root) {\n // well, it means we add a node to the end (inorder)\n return;\n }\n // x is the node whose right subtree is changed.\n x = x.parent;\n delta = calculateSize(x.left) - x.size_left;\n lf_delta = calculateLF(x.left) - x.lf_left;\n x.size_left += delta;\n x.lf_left += lf_delta;\n }\n // go upwards till root. O(logN)\n while (x !== tree.root && (delta !== 0 || lf_delta !== 0)) {\n if (x.parent.left === x) {\n x.parent.size_left += delta;\n x.parent.lf_left += lf_delta;\n }\n x = x.parent;\n }\n}\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport * as strings from '../../../base/common/strings.js';\nimport { getMapForWordSeparators } from '../controller/wordCharacterClassifier.js';\nimport { Position } from '../core/position.js';\nimport { Range } from '../core/range.js';\nimport { FindMatch } from '../model.js';\nvar LIMIT_FIND_COUNT = 999;\nvar SearchParams = /** @class */ (function () {\n function SearchParams(searchString, isRegex, matchCase, wordSeparators) {\n this.searchString = searchString;\n this.isRegex = isRegex;\n this.matchCase = matchCase;\n this.wordSeparators = wordSeparators;\n }\n SearchParams.prototype.parseSearchRequest = function () {\n if (this.searchString === '') {\n return null;\n }\n // Try to create a RegExp out of the params\n var multiline;\n if (this.isRegex) {\n multiline = isMultilineRegexSource(this.searchString);\n }\n else {\n multiline = (this.searchString.indexOf('\\n') >= 0);\n }\n var regex = null;\n try {\n regex = strings.createRegExp(this.searchString, this.isRegex, {\n matchCase: this.matchCase,\n wholeWord: false,\n multiline: multiline,\n global: true\n });\n }\n catch (err) {\n return null;\n }\n if (!regex) {\n return null;\n }\n var canUseSimpleSearch = (!this.isRegex && !multiline);\n if (canUseSimpleSearch && this.searchString.toLowerCase() !== this.searchString.toUpperCase()) {\n // casing might make a difference\n canUseSimpleSearch = this.matchCase;\n }\n return new SearchData(regex, this.wordSeparators ? getMapForWordSeparators(this.wordSeparators) : null, canUseSimpleSearch ? this.searchString : null);\n };\n return SearchParams;\n}());\nexport { SearchParams };\nexport function isMultilineRegexSource(searchString) {\n if (!searchString || searchString.length === 0) {\n return false;\n }\n for (var i = 0, len = searchString.length; i < len; i++) {\n var chCode = searchString.charCodeAt(i);\n if (chCode === 92 /* Backslash */) {\n // move to next char\n i++;\n if (i >= len) {\n // string ends with a \\\n break;\n }\n var nextChCode = searchString.charCodeAt(i);\n if (nextChCode === 110 /* n */ || nextChCode === 114 /* r */ || nextChCode === 87 /* W */) {\n return true;\n }\n }\n }\n return false;\n}\nvar SearchData = /** @class */ (function () {\n function SearchData(regex, wordSeparators, simpleSearch) {\n this.regex = regex;\n this.wordSeparators = wordSeparators;\n this.simpleSearch = simpleSearch;\n }\n return SearchData;\n}());\nexport { SearchData };\nexport function createFindMatch(range, rawMatches, captureMatches) {\n if (!captureMatches) {\n return new FindMatch(range, null);\n }\n var matches = [];\n for (var i = 0, len = rawMatches.length; i < len; i++) {\n matches[i] = rawMatches[i];\n }\n return new FindMatch(range, matches);\n}\nvar LineFeedCounter = /** @class */ (function () {\n function LineFeedCounter(text) {\n var lineFeedsOffsets = [];\n var lineFeedsOffsetsLen = 0;\n for (var i = 0, textLen = text.length; i < textLen; i++) {\n if (text.charCodeAt(i) === 10 /* LineFeed */) {\n lineFeedsOffsets[lineFeedsOffsetsLen++] = i;\n }\n }\n this._lineFeedsOffsets = lineFeedsOffsets;\n }\n LineFeedCounter.prototype.findLineFeedCountBeforeOffset = function (offset) {\n var lineFeedsOffsets = this._lineFeedsOffsets;\n var min = 0;\n var max = lineFeedsOffsets.length - 1;\n if (max === -1) {\n // no line feeds\n return 0;\n }\n if (offset <= lineFeedsOffsets[0]) {\n // before first line feed\n return 0;\n }\n while (min < max) {\n var mid = min + ((max - min) / 2 >> 0);\n if (lineFeedsOffsets[mid] >= offset) {\n max = mid - 1;\n }\n else {\n if (lineFeedsOffsets[mid + 1] >= offset) {\n // bingo!\n min = mid;\n max = mid;\n }\n else {\n min = mid + 1;\n }\n }\n }\n return min + 1;\n };\n return LineFeedCounter;\n}());\nvar TextModelSearch = /** @class */ (function () {\n function TextModelSearch() {\n }\n TextModelSearch.findMatches = function (model, searchParams, searchRange, captureMatches, limitResultCount) {\n var searchData = searchParams.parseSearchRequest();\n if (!searchData) {\n return [];\n }\n if (searchData.regex.multiline) {\n return this._doFindMatchesMultiline(model, searchRange, new Searcher(searchData.wordSeparators, searchData.regex), captureMatches, limitResultCount);\n }\n return this._doFindMatchesLineByLine(model, searchRange, searchData, captureMatches, limitResultCount);\n };\n /**\n * Multiline search always executes on the lines concatenated with \\n.\n * We must therefore compensate for the count of \\n in case the model is CRLF\n */\n TextModelSearch._getMultilineMatchRange = function (model, deltaOffset, text, lfCounter, matchIndex, match0) {\n var startOffset;\n var lineFeedCountBeforeMatch = 0;\n if (lfCounter) {\n lineFeedCountBeforeMatch = lfCounter.findLineFeedCountBeforeOffset(matchIndex);\n startOffset = deltaOffset + matchIndex + lineFeedCountBeforeMatch /* add as many \\r as there were \\n */;\n }\n else {\n startOffset = deltaOffset + matchIndex;\n }\n var endOffset;\n if (lfCounter) {\n var lineFeedCountBeforeEndOfMatch = lfCounter.findLineFeedCountBeforeOffset(matchIndex + match0.length);\n var lineFeedCountInMatch = lineFeedCountBeforeEndOfMatch - lineFeedCountBeforeMatch;\n endOffset = startOffset + match0.length + lineFeedCountInMatch /* add as many \\r as there were \\n */;\n }\n else {\n endOffset = startOffset + match0.length;\n }\n var startPosition = model.getPositionAt(startOffset);\n var endPosition = model.getPositionAt(endOffset);\n return new Range(startPosition.lineNumber, startPosition.column, endPosition.lineNumber, endPosition.column);\n };\n TextModelSearch._doFindMatchesMultiline = function (model, searchRange, searcher, captureMatches, limitResultCount) {\n var deltaOffset = model.getOffsetAt(searchRange.getStartPosition());\n // We always execute multiline search over the lines joined with \\n\n // This makes it that \\n will match the EOL for both CRLF and LF models\n // We compensate for offset errors in `_getMultilineMatchRange`\n var text = model.getValueInRange(searchRange, 1 /* LF */);\n var lfCounter = (model.getEOL() === '\\r\\n' ? new LineFeedCounter(text) : null);\n var result = [];\n var counter = 0;\n var m;\n searcher.reset(0);\n while ((m = searcher.next(text))) {\n result[counter++] = createFindMatch(this._getMultilineMatchRange(model, deltaOffset, text, lfCounter, m.index, m[0]), m, captureMatches);\n if (counter >= limitResultCount) {\n return result;\n }\n }\n return result;\n };\n TextModelSearch._doFindMatchesLineByLine = function (model, searchRange, searchData, captureMatches, limitResultCount) {\n var result = [];\n var resultLen = 0;\n // Early case for a search range that starts & stops on the same line number\n if (searchRange.startLineNumber === searchRange.endLineNumber) {\n var text_1 = model.getLineContent(searchRange.startLineNumber).substring(searchRange.startColumn - 1, searchRange.endColumn - 1);\n resultLen = this._findMatchesInLine(searchData, text_1, searchRange.startLineNumber, searchRange.startColumn - 1, resultLen, result, captureMatches, limitResultCount);\n return result;\n }\n // Collect results from first line\n var text = model.getLineContent(searchRange.startLineNumber).substring(searchRange.startColumn - 1);\n resultLen = this._findMatchesInLine(searchData, text, searchRange.startLineNumber, searchRange.startColumn - 1, resultLen, result, captureMatches, limitResultCount);\n // Collect results from middle lines\n for (var lineNumber = searchRange.startLineNumber + 1; lineNumber < searchRange.endLineNumber && resultLen < limitResultCount; lineNumber++) {\n resultLen = this._findMatchesInLine(searchData, model.getLineContent(lineNumber), lineNumber, 0, resultLen, result, captureMatches, limitResultCount);\n }\n // Collect results from last line\n if (resultLen < limitResultCount) {\n var text_2 = model.getLineContent(searchRange.endLineNumber).substring(0, searchRange.endColumn - 1);\n resultLen = this._findMatchesInLine(searchData, text_2, searchRange.endLineNumber, 0, resultLen, result, captureMatches, limitResultCount);\n }\n return result;\n };\n TextModelSearch._findMatchesInLine = function (searchData, text, lineNumber, deltaOffset, resultLen, result, captureMatches, limitResultCount) {\n var wordSeparators = searchData.wordSeparators;\n if (!captureMatches && searchData.simpleSearch) {\n var searchString = searchData.simpleSearch;\n var searchStringLen = searchString.length;\n var textLength = text.length;\n var lastMatchIndex = -searchStringLen;\n while ((lastMatchIndex = text.indexOf(searchString, lastMatchIndex + searchStringLen)) !== -1) {\n if (!wordSeparators || isValidMatch(wordSeparators, text, textLength, lastMatchIndex, searchStringLen)) {\n result[resultLen++] = new FindMatch(new Range(lineNumber, lastMatchIndex + 1 + deltaOffset, lineNumber, lastMatchIndex + 1 + searchStringLen + deltaOffset), null);\n if (resultLen >= limitResultCount) {\n return resultLen;\n }\n }\n }\n return resultLen;\n }\n var searcher = new Searcher(searchData.wordSeparators, searchData.regex);\n var m;\n // Reset regex to search from the beginning\n searcher.reset(0);\n do {\n m = searcher.next(text);\n if (m) {\n result[resultLen++] = createFindMatch(new Range(lineNumber, m.index + 1 + deltaOffset, lineNumber, m.index + 1 + m[0].length + deltaOffset), m, captureMatches);\n if (resultLen >= limitResultCount) {\n return resultLen;\n }\n }\n } while (m);\n return resultLen;\n };\n TextModelSearch.findNextMatch = function (model, searchParams, searchStart, captureMatches) {\n var searchData = searchParams.parseSearchRequest();\n if (!searchData) {\n return null;\n }\n var searcher = new Searcher(searchData.wordSeparators, searchData.regex);\n if (searchData.regex.multiline) {\n return this._doFindNextMatchMultiline(model, searchStart, searcher, captureMatches);\n }\n return this._doFindNextMatchLineByLine(model, searchStart, searcher, captureMatches);\n };\n TextModelSearch._doFindNextMatchMultiline = function (model, searchStart, searcher, captureMatches) {\n var searchTextStart = new Position(searchStart.lineNumber, 1);\n var deltaOffset = model.getOffsetAt(searchTextStart);\n var lineCount = model.getLineCount();\n // We always execute multiline search over the lines joined with \\n\n // This makes it that \\n will match the EOL for both CRLF and LF models\n // We compensate for offset errors in `_getMultilineMatchRange`\n var text = model.getValueInRange(new Range(searchTextStart.lineNumber, searchTextStart.column, lineCount, model.getLineMaxColumn(lineCount)), 1 /* LF */);\n var lfCounter = (model.getEOL() === '\\r\\n' ? new LineFeedCounter(text) : null);\n searcher.reset(searchStart.column - 1);\n var m = searcher.next(text);\n if (m) {\n return createFindMatch(this._getMultilineMatchRange(model, deltaOffset, text, lfCounter, m.index, m[0]), m, captureMatches);\n }\n if (searchStart.lineNumber !== 1 || searchStart.column !== 1) {\n // Try again from the top\n return this._doFindNextMatchMultiline(model, new Position(1, 1), searcher, captureMatches);\n }\n return null;\n };\n TextModelSearch._doFindNextMatchLineByLine = function (model, searchStart, searcher, captureMatches) {\n var lineCount = model.getLineCount();\n var startLineNumber = searchStart.lineNumber;\n // Look in first line\n var text = model.getLineContent(startLineNumber);\n var r = this._findFirstMatchInLine(searcher, text, startLineNumber, searchStart.column, captureMatches);\n if (r) {\n return r;\n }\n for (var i = 1; i <= lineCount; i++) {\n var lineIndex = (startLineNumber + i - 1) % lineCount;\n var text_3 = model.getLineContent(lineIndex + 1);\n var r_1 = this._findFirstMatchInLine(searcher, text_3, lineIndex + 1, 1, captureMatches);\n if (r_1) {\n return r_1;\n }\n }\n return null;\n };\n TextModelSearch._findFirstMatchInLine = function (searcher, text, lineNumber, fromColumn, captureMatches) {\n // Set regex to search from column\n searcher.reset(fromColumn - 1);\n var m = searcher.next(text);\n if (m) {\n return createFindMatch(new Range(lineNumber, m.index + 1, lineNumber, m.index + 1 + m[0].length), m, captureMatches);\n }\n return null;\n };\n TextModelSearch.findPreviousMatch = function (model, searchParams, searchStart, captureMatches) {\n var searchData = searchParams.parseSearchRequest();\n if (!searchData) {\n return null;\n }\n var searcher = new Searcher(searchData.wordSeparators, searchData.regex);\n if (searchData.regex.multiline) {\n return this._doFindPreviousMatchMultiline(model, searchStart, searcher, captureMatches);\n }\n return this._doFindPreviousMatchLineByLine(model, searchStart, searcher, captureMatches);\n };\n TextModelSearch._doFindPreviousMatchMultiline = function (model, searchStart, searcher, captureMatches) {\n var matches = this._doFindMatchesMultiline(model, new Range(1, 1, searchStart.lineNumber, searchStart.column), searcher, captureMatches, 10 * LIMIT_FIND_COUNT);\n if (matches.length > 0) {\n return matches[matches.length - 1];\n }\n var lineCount = model.getLineCount();\n if (searchStart.lineNumber !== lineCount || searchStart.column !== model.getLineMaxColumn(lineCount)) {\n // Try again with all content\n return this._doFindPreviousMatchMultiline(model, new Position(lineCount, model.getLineMaxColumn(lineCount)), searcher, captureMatches);\n }\n return null;\n };\n TextModelSearch._doFindPreviousMatchLineByLine = function (model, searchStart, searcher, captureMatches) {\n var lineCount = model.getLineCount();\n var startLineNumber = searchStart.lineNumber;\n // Look in first line\n var text = model.getLineContent(startLineNumber).substring(0, searchStart.column - 1);\n var r = this._findLastMatchInLine(searcher, text, startLineNumber, captureMatches);\n if (r) {\n return r;\n }\n for (var i = 1; i <= lineCount; i++) {\n var lineIndex = (lineCount + startLineNumber - i - 1) % lineCount;\n var text_4 = model.getLineContent(lineIndex + 1);\n var r_2 = this._findLastMatchInLine(searcher, text_4, lineIndex + 1, captureMatches);\n if (r_2) {\n return r_2;\n }\n }\n return null;\n };\n TextModelSearch._findLastMatchInLine = function (searcher, text, lineNumber, captureMatches) {\n var bestResult = null;\n var m;\n searcher.reset(0);\n while ((m = searcher.next(text))) {\n bestResult = createFindMatch(new Range(lineNumber, m.index + 1, lineNumber, m.index + 1 + m[0].length), m, captureMatches);\n }\n return bestResult;\n };\n return TextModelSearch;\n}());\nexport { TextModelSearch };\nfunction leftIsWordBounday(wordSeparators, text, textLength, matchStartIndex, matchLength) {\n if (matchStartIndex === 0) {\n // Match starts at start of string\n return true;\n }\n var charBefore = text.charCodeAt(matchStartIndex - 1);\n if (wordSeparators.get(charBefore) !== 0 /* Regular */) {\n // The character before the match is a word separator\n return true;\n }\n if (charBefore === 13 /* CarriageReturn */ || charBefore === 10 /* LineFeed */) {\n // The character before the match is line break or carriage return.\n return true;\n }\n if (matchLength > 0) {\n var firstCharInMatch = text.charCodeAt(matchStartIndex);\n if (wordSeparators.get(firstCharInMatch) !== 0 /* Regular */) {\n // The first character inside the match is a word separator\n return true;\n }\n }\n return false;\n}\nfunction rightIsWordBounday(wordSeparators, text, textLength, matchStartIndex, matchLength) {\n if (matchStartIndex + matchLength === textLength) {\n // Match ends at end of string\n return true;\n }\n var charAfter = text.charCodeAt(matchStartIndex + matchLength);\n if (wordSeparators.get(charAfter) !== 0 /* Regular */) {\n // The character after the match is a word separator\n return true;\n }\n if (charAfter === 13 /* CarriageReturn */ || charAfter === 10 /* LineFeed */) {\n // The character after the match is line break or carriage return.\n return true;\n }\n if (matchLength > 0) {\n var lastCharInMatch = text.charCodeAt(matchStartIndex + matchLength - 1);\n if (wordSeparators.get(lastCharInMatch) !== 0 /* Regular */) {\n // The last character in the match is a word separator\n return true;\n }\n }\n return false;\n}\nexport function isValidMatch(wordSeparators, text, textLength, matchStartIndex, matchLength) {\n return (leftIsWordBounday(wordSeparators, text, textLength, matchStartIndex, matchLength)\n && rightIsWordBounday(wordSeparators, text, textLength, matchStartIndex, matchLength));\n}\nvar Searcher = /** @class */ (function () {\n function Searcher(wordSeparators, searchRegex) {\n this._wordSeparators = wordSeparators;\n this._searchRegex = searchRegex;\n this._prevMatchStartIndex = -1;\n this._prevMatchLength = 0;\n }\n Searcher.prototype.reset = function (lastIndex) {\n this._searchRegex.lastIndex = lastIndex;\n this._prevMatchStartIndex = -1;\n this._prevMatchLength = 0;\n };\n Searcher.prototype.next = function (text) {\n var textLength = text.length;\n var m;\n do {\n if (this._prevMatchStartIndex + this._prevMatchLength === textLength) {\n // Reached the end of the line\n return null;\n }\n m = this._searchRegex.exec(text);\n if (!m) {\n return null;\n }\n var matchStartIndex = m.index;\n var matchLength = m[0].length;\n if (matchStartIndex === this._prevMatchStartIndex && matchLength === this._prevMatchLength) {\n // Exit early if the regex matches the same range twice\n return null;\n }\n this._prevMatchStartIndex = matchStartIndex;\n this._prevMatchLength = matchLength;\n if (!this._wordSeparators || isValidMatch(this._wordSeparators, text, textLength, matchStartIndex, matchLength)) {\n return m;\n }\n } while (m);\n return null;\n };\n return Searcher;\n}());\nexport { Searcher };\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport { Position } from '../../core/position.js';\nimport { Range } from '../../core/range.js';\nimport { FindMatch } from '../../model.js';\nimport { SENTINEL, TreeNode, fixInsert, leftest, rbDelete, righttest, updateTreeMetadata } from './rbTreeBase.js';\nimport { Searcher, createFindMatch, isValidMatch } from '../textModelSearch.js';\n// const lfRegex = new RegExp(/\\r\\n|\\r|\\n/g);\nexport var AverageBufferSize = 65535;\nexport function createUintArray(arr) {\n var r;\n if (arr[arr.length - 1] < 65536) {\n r = new Uint16Array(arr.length);\n }\n else {\n r = new Uint32Array(arr.length);\n }\n r.set(arr, 0);\n return r;\n}\nvar LineStarts = /** @class */ (function () {\n function LineStarts(lineStarts, cr, lf, crlf, isBasicASCII) {\n this.lineStarts = lineStarts;\n this.cr = cr;\n this.lf = lf;\n this.crlf = crlf;\n this.isBasicASCII = isBasicASCII;\n }\n return LineStarts;\n}());\nexport { LineStarts };\nexport function createLineStartsFast(str, readonly) {\n if (readonly === void 0) { readonly = true; }\n var r = [0], rLength = 1;\n for (var i = 0, len = str.length; i < len; i++) {\n var chr = str.charCodeAt(i);\n if (chr === 13 /* CarriageReturn */) {\n if (i + 1 < len && str.charCodeAt(i + 1) === 10 /* LineFeed */) {\n // \\r\\n... case\n r[rLength++] = i + 2;\n i++; // skip \\n\n }\n else {\n // \\r... case\n r[rLength++] = i + 1;\n }\n }\n else if (chr === 10 /* LineFeed */) {\n r[rLength++] = i + 1;\n }\n }\n if (readonly) {\n return createUintArray(r);\n }\n else {\n return r;\n }\n}\nexport function createLineStarts(r, str) {\n r.length = 0;\n r[0] = 0;\n var rLength = 1;\n var cr = 0, lf = 0, crlf = 0;\n var isBasicASCII = true;\n for (var i = 0, len = str.length; i < len; i++) {\n var chr = str.charCodeAt(i);\n if (chr === 13 /* CarriageReturn */) {\n if (i + 1 < len && str.charCodeAt(i + 1) === 10 /* LineFeed */) {\n // \\r\\n... case\n crlf++;\n r[rLength++] = i + 2;\n i++; // skip \\n\n }\n else {\n cr++;\n // \\r... case\n r[rLength++] = i + 1;\n }\n }\n else if (chr === 10 /* LineFeed */) {\n lf++;\n r[rLength++] = i + 1;\n }\n else {\n if (isBasicASCII) {\n if (chr !== 9 /* Tab */ && (chr < 32 || chr > 126)) {\n isBasicASCII = false;\n }\n }\n }\n }\n var result = new LineStarts(createUintArray(r), cr, lf, crlf, isBasicASCII);\n r.length = 0;\n return result;\n}\nvar Piece = /** @class */ (function () {\n function Piece(bufferIndex, start, end, lineFeedCnt, length) {\n this.bufferIndex = bufferIndex;\n this.start = start;\n this.end = end;\n this.lineFeedCnt = lineFeedCnt;\n this.length = length;\n }\n return Piece;\n}());\nexport { Piece };\nvar StringBuffer = /** @class */ (function () {\n function StringBuffer(buffer, lineStarts) {\n this.buffer = buffer;\n this.lineStarts = lineStarts;\n }\n return StringBuffer;\n}());\nexport { StringBuffer };\nvar PieceTreeSearchCache = /** @class */ (function () {\n function PieceTreeSearchCache(limit) {\n this._limit = limit;\n this._cache = [];\n }\n PieceTreeSearchCache.prototype.get = function (offset) {\n for (var i = this._cache.length - 1; i >= 0; i--) {\n var nodePos = this._cache[i];\n if (nodePos.nodeStartOffset <= offset && nodePos.nodeStartOffset + nodePos.node.piece.length >= offset) {\n return nodePos;\n }\n }\n return null;\n };\n PieceTreeSearchCache.prototype.get2 = function (lineNumber) {\n for (var i = this._cache.length - 1; i >= 0; i--) {\n var nodePos = this._cache[i];\n if (nodePos.nodeStartLineNumber && nodePos.nodeStartLineNumber < lineNumber && nodePos.nodeStartLineNumber + nodePos.node.piece.lineFeedCnt >= lineNumber) {\n return nodePos;\n }\n }\n return null;\n };\n PieceTreeSearchCache.prototype.set = function (nodePosition) {\n if (this._cache.length >= this._limit) {\n this._cache.shift();\n }\n this._cache.push(nodePosition);\n };\n PieceTreeSearchCache.prototype.valdiate = function (offset) {\n var hasInvalidVal = false;\n var tmp = this._cache;\n for (var i = 0; i < tmp.length; i++) {\n var nodePos = tmp[i];\n if (nodePos.node.parent === null || nodePos.nodeStartOffset >= offset) {\n tmp[i] = null;\n hasInvalidVal = true;\n continue;\n }\n }\n if (hasInvalidVal) {\n var newArr = [];\n for (var _i = 0, tmp_1 = tmp; _i < tmp_1.length; _i++) {\n var entry = tmp_1[_i];\n if (entry !== null) {\n newArr.push(entry);\n }\n }\n this._cache = newArr;\n }\n };\n return PieceTreeSearchCache;\n}());\nvar PieceTreeBase = /** @class */ (function () {\n function PieceTreeBase(chunks, eol, eolNormalized) {\n this.create(chunks, eol, eolNormalized);\n }\n PieceTreeBase.prototype.create = function (chunks, eol, eolNormalized) {\n this._buffers = [\n new StringBuffer('', [0])\n ];\n this._lastChangeBufferPos = { line: 0, column: 0 };\n this.root = SENTINEL;\n this._lineCnt = 1;\n this._length = 0;\n this._EOL = eol;\n this._EOLLength = eol.length;\n this._EOLNormalized = eolNormalized;\n var lastNode = null;\n for (var i = 0, len = chunks.length; i < len; i++) {\n if (chunks[i].buffer.length > 0) {\n if (!chunks[i].lineStarts) {\n chunks[i].lineStarts = createLineStartsFast(chunks[i].buffer);\n }\n var piece = new Piece(i + 1, { line: 0, column: 0 }, { line: chunks[i].lineStarts.length - 1, column: chunks[i].buffer.length - chunks[i].lineStarts[chunks[i].lineStarts.length - 1] }, chunks[i].lineStarts.length - 1, chunks[i].buffer.length);\n this._buffers.push(chunks[i]);\n lastNode = this.rbInsertRight(lastNode, piece);\n }\n }\n this._searchCache = new PieceTreeSearchCache(1);\n this._lastVisitedLine = { lineNumber: 0, value: '' };\n this.computeBufferMetadata();\n };\n PieceTreeBase.prototype.normalizeEOL = function (eol) {\n var _this = this;\n var averageBufferSize = AverageBufferSize;\n var min = averageBufferSize - Math.floor(averageBufferSize / 3);\n var max = min * 2;\n var tempChunk = '';\n var tempChunkLen = 0;\n var chunks = [];\n this.iterate(this.root, function (node) {\n var str = _this.getNodeContent(node);\n var len = str.length;\n if (tempChunkLen <= min || tempChunkLen + len < max) {\n tempChunk += str;\n tempChunkLen += len;\n return true;\n }\n // flush anyways\n var text = tempChunk.replace(/\\r\\n|\\r|\\n/g, eol);\n chunks.push(new StringBuffer(text, createLineStartsFast(text)));\n tempChunk = str;\n tempChunkLen = len;\n return true;\n });\n if (tempChunkLen > 0) {\n var text = tempChunk.replace(/\\r\\n|\\r|\\n/g, eol);\n chunks.push(new StringBuffer(text, createLineStartsFast(text)));\n }\n this.create(chunks, eol, true);\n };\n // #region Buffer API\n PieceTreeBase.prototype.getEOL = function () {\n return this._EOL;\n };\n PieceTreeBase.prototype.setEOL = function (newEOL) {\n this._EOL = newEOL;\n this._EOLLength = this._EOL.length;\n this.normalizeEOL(newEOL);\n };\n PieceTreeBase.prototype.getOffsetAt = function (lineNumber, column) {\n var leftLen = 0; // inorder\n var x = this.root;\n while (x !== SENTINEL) {\n if (x.left !== SENTINEL && x.lf_left + 1 >= lineNumber) {\n x = x.left;\n }\n else if (x.lf_left + x.piece.lineFeedCnt + 1 >= lineNumber) {\n leftLen += x.size_left;\n // lineNumber >= 2\n var accumualtedValInCurrentIndex = this.getAccumulatedValue(x, lineNumber - x.lf_left - 2);\n return leftLen += accumualtedValInCurrentIndex + column - 1;\n }\n else {\n lineNumber -= x.lf_left + x.piece.lineFeedCnt;\n leftLen += x.size_left + x.piece.length;\n x = x.right;\n }\n }\n return leftLen;\n };\n PieceTreeBase.prototype.getPositionAt = function (offset) {\n offset = Math.floor(offset);\n offset = Math.max(0, offset);\n var x = this.root;\n var lfCnt = 0;\n var originalOffset = offset;\n while (x !== SENTINEL) {\n if (x.size_left !== 0 && x.size_left >= offset) {\n x = x.left;\n }\n else if (x.size_left + x.piece.length >= offset) {\n var out = this.getIndexOf(x, offset - x.size_left);\n lfCnt += x.lf_left + out.index;\n if (out.index === 0) {\n var lineStartOffset = this.getOffsetAt(lfCnt + 1, 1);\n var column = originalOffset - lineStartOffset;\n return new Position(lfCnt + 1, column + 1);\n }\n return new Position(lfCnt + 1, out.remainder + 1);\n }\n else {\n offset -= x.size_left + x.piece.length;\n lfCnt += x.lf_left + x.piece.lineFeedCnt;\n if (x.right === SENTINEL) {\n // last node\n var lineStartOffset = this.getOffsetAt(lfCnt + 1, 1);\n var column = originalOffset - offset - lineStartOffset;\n return new Position(lfCnt + 1, column + 1);\n }\n else {\n x = x.right;\n }\n }\n }\n return new Position(1, 1);\n };\n PieceTreeBase.prototype.getValueInRange = function (range, eol) {\n if (range.startLineNumber === range.endLineNumber && range.startColumn === range.endColumn) {\n return '';\n }\n var startPosition = this.nodeAt2(range.startLineNumber, range.startColumn);\n var endPosition = this.nodeAt2(range.endLineNumber, range.endColumn);\n var value = this.getValueInRange2(startPosition, endPosition);\n if (eol) {\n if (eol !== this._EOL || !this._EOLNormalized) {\n return value.replace(/\\r\\n|\\r|\\n/g, eol);\n }\n if (eol === this.getEOL() && this._EOLNormalized) {\n if (eol === '\\r\\n') {\n }\n return value;\n }\n return value.replace(/\\r\\n|\\r|\\n/g, eol);\n }\n return value;\n };\n PieceTreeBase.prototype.getValueInRange2 = function (startPosition, endPosition) {\n if (startPosition.node === endPosition.node) {\n var node = startPosition.node;\n var buffer_1 = this._buffers[node.piece.bufferIndex].buffer;\n var startOffset_1 = this.offsetInBuffer(node.piece.bufferIndex, node.piece.start);\n return buffer_1.substring(startOffset_1 + startPosition.remainder, startOffset_1 + endPosition.remainder);\n }\n var x = startPosition.node;\n var buffer = this._buffers[x.piece.bufferIndex].buffer;\n var startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start);\n var ret = buffer.substring(startOffset + startPosition.remainder, startOffset + x.piece.length);\n x = x.next();\n while (x !== SENTINEL) {\n var buffer_2 = this._buffers[x.piece.bufferIndex].buffer;\n var startOffset_2 = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start);\n if (x === endPosition.node) {\n ret += buffer_2.substring(startOffset_2, startOffset_2 + endPosition.remainder);\n break;\n }\n else {\n ret += buffer_2.substr(startOffset_2, x.piece.length);\n }\n x = x.next();\n }\n return ret;\n };\n PieceTreeBase.prototype.getLinesContent = function () {\n return this.getContentOfSubTree(this.root).split(/\\r\\n|\\r|\\n/);\n };\n PieceTreeBase.prototype.getLength = function () {\n return this._length;\n };\n PieceTreeBase.prototype.getLineCount = function () {\n return this._lineCnt;\n };\n PieceTreeBase.prototype.getLineContent = function (lineNumber) {\n if (this._lastVisitedLine.lineNumber === lineNumber) {\n return this._lastVisitedLine.value;\n }\n this._lastVisitedLine.lineNumber = lineNumber;\n if (lineNumber === this._lineCnt) {\n this._lastVisitedLine.value = this.getLineRawContent(lineNumber);\n }\n else if (this._EOLNormalized) {\n this._lastVisitedLine.value = this.getLineRawContent(lineNumber, this._EOLLength);\n }\n else {\n this._lastVisitedLine.value = this.getLineRawContent(lineNumber).replace(/(\\r\\n|\\r|\\n)$/, '');\n }\n return this._lastVisitedLine.value;\n };\n PieceTreeBase.prototype.getLineCharCode = function (lineNumber, index) {\n var nodePos = this.nodeAt2(lineNumber, index + 1);\n if (nodePos.remainder === nodePos.node.piece.length) {\n // the char we want to fetch is at the head of next node.\n var matchingNode = nodePos.node.next();\n if (!matchingNode) {\n return 0;\n }\n var buffer = this._buffers[matchingNode.piece.bufferIndex];\n var startOffset = this.offsetInBuffer(matchingNode.piece.bufferIndex, matchingNode.piece.start);\n return buffer.buffer.charCodeAt(startOffset);\n }\n else {\n var buffer = this._buffers[nodePos.node.piece.bufferIndex];\n var startOffset = this.offsetInBuffer(nodePos.node.piece.bufferIndex, nodePos.node.piece.start);\n var targetOffset = startOffset + nodePos.remainder;\n return buffer.buffer.charCodeAt(targetOffset);\n }\n };\n PieceTreeBase.prototype.getLineLength = function (lineNumber) {\n if (lineNumber === this.getLineCount()) {\n var startOffset = this.getOffsetAt(lineNumber, 1);\n return this.getLength() - startOffset;\n }\n return this.getOffsetAt(lineNumber + 1, 1) - this.getOffsetAt(lineNumber, 1) - this._EOLLength;\n };\n PieceTreeBase.prototype.findMatchesInNode = function (node, searcher, startLineNumber, startColumn, startCursor, endCursor, searchData, captureMatches, limitResultCount, resultLen, result) {\n var buffer = this._buffers[node.piece.bufferIndex];\n var startOffsetInBuffer = this.offsetInBuffer(node.piece.bufferIndex, node.piece.start);\n var start = this.offsetInBuffer(node.piece.bufferIndex, startCursor);\n var end = this.offsetInBuffer(node.piece.bufferIndex, endCursor);\n var m;\n // Reset regex to search from the beginning\n searcher.reset(start);\n var ret = { line: 0, column: 0 };\n do {\n m = searcher.next(buffer.buffer);\n if (m) {\n if (m.index >= end) {\n return resultLen;\n }\n this.positionInBuffer(node, m.index - startOffsetInBuffer, ret);\n var lineFeedCnt = this.getLineFeedCnt(node.piece.bufferIndex, startCursor, ret);\n var retStartColumn = ret.line === startCursor.line ? ret.column - startCursor.column + startColumn : ret.column + 1;\n var retEndColumn = retStartColumn + m[0].length;\n result[resultLen++] = createFindMatch(new Range(startLineNumber + lineFeedCnt, retStartColumn, startLineNumber + lineFeedCnt, retEndColumn), m, captureMatches);\n if (m.index + m[0].length >= end) {\n return resultLen;\n }\n if (resultLen >= limitResultCount) {\n return resultLen;\n }\n }\n } while (m);\n return resultLen;\n };\n PieceTreeBase.prototype.findMatchesLineByLine = function (searchRange, searchData, captureMatches, limitResultCount) {\n var result = [];\n var resultLen = 0;\n var searcher = new Searcher(searchData.wordSeparators, searchData.regex);\n var startPostion = this.nodeAt2(searchRange.startLineNumber, searchRange.startColumn);\n if (startPostion === null) {\n return [];\n }\n var endPosition = this.nodeAt2(searchRange.endLineNumber, searchRange.endColumn);\n if (endPosition === null) {\n return [];\n }\n var start = this.positionInBuffer(startPostion.node, startPostion.remainder);\n var end = this.positionInBuffer(endPosition.node, endPosition.remainder);\n if (startPostion.node === endPosition.node) {\n this.findMatchesInNode(startPostion.node, searcher, searchRange.startLineNumber, searchRange.startColumn, start, end, searchData, captureMatches, limitResultCount, resultLen, result);\n return result;\n }\n var startLineNumber = searchRange.startLineNumber;\n var currentNode = startPostion.node;\n while (currentNode !== endPosition.node) {\n var lineBreakCnt = this.getLineFeedCnt(currentNode.piece.bufferIndex, start, currentNode.piece.end);\n if (lineBreakCnt >= 1) {\n // last line break position\n var lineStarts = this._buffers[currentNode.piece.bufferIndex].lineStarts;\n var startOffsetInBuffer = this.offsetInBuffer(currentNode.piece.bufferIndex, currentNode.piece.start);\n var nextLineStartOffset = lineStarts[start.line + lineBreakCnt];\n var startColumn_1 = startLineNumber === searchRange.startLineNumber ? searchRange.startColumn : 1;\n resultLen = this.findMatchesInNode(currentNode, searcher, startLineNumber, startColumn_1, start, this.positionInBuffer(currentNode, nextLineStartOffset - startOffsetInBuffer), searchData, captureMatches, limitResultCount, resultLen, result);\n if (resultLen >= limitResultCount) {\n return result;\n }\n startLineNumber += lineBreakCnt;\n }\n var startColumn_2 = startLineNumber === searchRange.startLineNumber ? searchRange.startColumn - 1 : 0;\n // search for the remaining content\n if (startLineNumber === searchRange.endLineNumber) {\n var text = this.getLineContent(startLineNumber).substring(startColumn_2, searchRange.endColumn - 1);\n resultLen = this._findMatchesInLine(searchData, searcher, text, searchRange.endLineNumber, startColumn_2, resultLen, result, captureMatches, limitResultCount);\n return result;\n }\n resultLen = this._findMatchesInLine(searchData, searcher, this.getLineContent(startLineNumber).substr(startColumn_2), startLineNumber, startColumn_2, resultLen, result, captureMatches, limitResultCount);\n if (resultLen >= limitResultCount) {\n return result;\n }\n startLineNumber++;\n startPostion = this.nodeAt2(startLineNumber, 1);\n currentNode = startPostion.node;\n start = this.positionInBuffer(startPostion.node, startPostion.remainder);\n }\n if (startLineNumber === searchRange.endLineNumber) {\n var startColumn_3 = startLineNumber === searchRange.startLineNumber ? searchRange.startColumn - 1 : 0;\n var text = this.getLineContent(startLineNumber).substring(startColumn_3, searchRange.endColumn - 1);\n resultLen = this._findMatchesInLine(searchData, searcher, text, searchRange.endLineNumber, startColumn_3, resultLen, result, captureMatches, limitResultCount);\n return result;\n }\n var startColumn = startLineNumber === searchRange.startLineNumber ? searchRange.startColumn : 1;\n resultLen = this.findMatchesInNode(endPosition.node, searcher, startLineNumber, startColumn, start, end, searchData, captureMatches, limitResultCount, resultLen, result);\n return result;\n };\n PieceTreeBase.prototype._findMatchesInLine = function (searchData, searcher, text, lineNumber, deltaOffset, resultLen, result, captureMatches, limitResultCount) {\n var wordSeparators = searchData.wordSeparators;\n if (!captureMatches && searchData.simpleSearch) {\n var searchString = searchData.simpleSearch;\n var searchStringLen = searchString.length;\n var textLength = text.length;\n var lastMatchIndex = -searchStringLen;\n while ((lastMatchIndex = text.indexOf(searchString, lastMatchIndex + searchStringLen)) !== -1) {\n if (!wordSeparators || isValidMatch(wordSeparators, text, textLength, lastMatchIndex, searchStringLen)) {\n result[resultLen++] = new FindMatch(new Range(lineNumber, lastMatchIndex + 1 + deltaOffset, lineNumber, lastMatchIndex + 1 + searchStringLen + deltaOffset), null);\n if (resultLen >= limitResultCount) {\n return resultLen;\n }\n }\n }\n return resultLen;\n }\n var m;\n // Reset regex to search from the beginning\n searcher.reset(0);\n do {\n m = searcher.next(text);\n if (m) {\n result[resultLen++] = createFindMatch(new Range(lineNumber, m.index + 1 + deltaOffset, lineNumber, m.index + 1 + m[0].length + deltaOffset), m, captureMatches);\n if (resultLen >= limitResultCount) {\n return resultLen;\n }\n }\n } while (m);\n return resultLen;\n };\n // #endregion\n // #region Piece Table\n PieceTreeBase.prototype.insert = function (offset, value, eolNormalized) {\n if (eolNormalized === void 0) { eolNormalized = false; }\n this._EOLNormalized = this._EOLNormalized && eolNormalized;\n this._lastVisitedLine.lineNumber = 0;\n this._lastVisitedLine.value = '';\n if (this.root !== SENTINEL) {\n var _a = this.nodeAt(offset), node = _a.node, remainder = _a.remainder, nodeStartOffset = _a.nodeStartOffset;\n var piece = node.piece;\n var bufferIndex = piece.bufferIndex;\n var insertPosInBuffer = this.positionInBuffer(node, remainder);\n if (node.piece.bufferIndex === 0 &&\n piece.end.line === this._lastChangeBufferPos.line &&\n piece.end.column === this._lastChangeBufferPos.column &&\n (nodeStartOffset + piece.length === offset) &&\n value.length < AverageBufferSize) {\n // changed buffer\n this.appendToNode(node, value);\n this.computeBufferMetadata();\n return;\n }\n if (nodeStartOffset === offset) {\n this.insertContentToNodeLeft(value, node);\n this._searchCache.valdiate(offset);\n }\n else if (nodeStartOffset + node.piece.length > offset) {\n // we are inserting into the middle of a node.\n var nodesToDel = [];\n var newRightPiece = new Piece(piece.bufferIndex, insertPosInBuffer, piece.end, this.getLineFeedCnt(piece.bufferIndex, insertPosInBuffer, piece.end), this.offsetInBuffer(bufferIndex, piece.end) - this.offsetInBuffer(bufferIndex, insertPosInBuffer));\n if (this.shouldCheckCRLF() && this.endWithCR(value)) {\n var headOfRight = this.nodeCharCodeAt(node, remainder);\n if (headOfRight === 10 /** \\n */) {\n var newStart = { line: newRightPiece.start.line + 1, column: 0 };\n newRightPiece = new Piece(newRightPiece.bufferIndex, newStart, newRightPiece.end, this.getLineFeedCnt(newRightPiece.bufferIndex, newStart, newRightPiece.end), newRightPiece.length - 1);\n value += '\\n';\n }\n }\n // reuse node for content before insertion point.\n if (this.shouldCheckCRLF() && this.startWithLF(value)) {\n var tailOfLeft = this.nodeCharCodeAt(node, remainder - 1);\n if (tailOfLeft === 13 /** \\r */) {\n var previousPos = this.positionInBuffer(node, remainder - 1);\n this.deleteNodeTail(node, previousPos);\n value = '\\r' + value;\n if (node.piece.length === 0) {\n nodesToDel.push(node);\n }\n }\n else {\n this.deleteNodeTail(node, insertPosInBuffer);\n }\n }\n else {\n this.deleteNodeTail(node, insertPosInBuffer);\n }\n var newPieces = this.createNewPieces(value);\n if (newRightPiece.length > 0) {\n this.rbInsertRight(node, newRightPiece);\n }\n var tmpNode = node;\n for (var k = 0; k < newPieces.length; k++) {\n tmpNode = this.rbInsertRight(tmpNode, newPieces[k]);\n }\n this.deleteNodes(nodesToDel);\n }\n else {\n this.insertContentToNodeRight(value, node);\n }\n }\n else {\n // insert new node\n var pieces = this.createNewPieces(value);\n var node = this.rbInsertLeft(null, pieces[0]);\n for (var k = 1; k < pieces.length; k++) {\n node = this.rbInsertRight(node, pieces[k]);\n }\n }\n // todo, this is too brutal. Total line feed count should be updated the same way as lf_left.\n this.computeBufferMetadata();\n };\n PieceTreeBase.prototype.delete = function (offset, cnt) {\n this._lastVisitedLine.lineNumber = 0;\n this._lastVisitedLine.value = '';\n if (cnt <= 0 || this.root === SENTINEL) {\n return;\n }\n var startPosition = this.nodeAt(offset);\n var endPosition = this.nodeAt(offset + cnt);\n var startNode = startPosition.node;\n var endNode = endPosition.node;\n if (startNode === endNode) {\n var startSplitPosInBuffer_1 = this.positionInBuffer(startNode, startPosition.remainder);\n var endSplitPosInBuffer_1 = this.positionInBuffer(startNode, endPosition.remainder);\n if (startPosition.nodeStartOffset === offset) {\n if (cnt === startNode.piece.length) { // delete node\n var next = startNode.next();\n rbDelete(this, startNode);\n this.validateCRLFWithPrevNode(next);\n this.computeBufferMetadata();\n return;\n }\n this.deleteNodeHead(startNode, endSplitPosInBuffer_1);\n this._searchCache.valdiate(offset);\n this.validateCRLFWithPrevNode(startNode);\n this.computeBufferMetadata();\n return;\n }\n if (startPosition.nodeStartOffset + startNode.piece.length === offset + cnt) {\n this.deleteNodeTail(startNode, startSplitPosInBuffer_1);\n this.validateCRLFWithNextNode(startNode);\n this.computeBufferMetadata();\n return;\n }\n // delete content in the middle, this node will be splitted to nodes\n this.shrinkNode(startNode, startSplitPosInBuffer_1, endSplitPosInBuffer_1);\n this.computeBufferMetadata();\n return;\n }\n var nodesToDel = [];\n var startSplitPosInBuffer = this.positionInBuffer(startNode, startPosition.remainder);\n this.deleteNodeTail(startNode, startSplitPosInBuffer);\n this._searchCache.valdiate(offset);\n if (startNode.piece.length === 0) {\n nodesToDel.push(startNode);\n }\n // update last touched node\n var endSplitPosInBuffer = this.positionInBuffer(endNode, endPosition.remainder);\n this.deleteNodeHead(endNode, endSplitPosInBuffer);\n if (endNode.piece.length === 0) {\n nodesToDel.push(endNode);\n }\n // delete nodes in between\n var secondNode = startNode.next();\n for (var node = secondNode; node !== SENTINEL && node !== endNode; node = node.next()) {\n nodesToDel.push(node);\n }\n var prev = startNode.piece.length === 0 ? startNode.prev() : startNode;\n this.deleteNodes(nodesToDel);\n this.validateCRLFWithNextNode(prev);\n this.computeBufferMetadata();\n };\n PieceTreeBase.prototype.insertContentToNodeLeft = function (value, node) {\n // we are inserting content to the beginning of node\n var nodesToDel = [];\n if (this.shouldCheckCRLF() && this.endWithCR(value) && this.startWithLF(node)) {\n // move `\\n` to new node.\n var piece = node.piece;\n var newStart = { line: piece.start.line + 1, column: 0 };\n var nPiece = new Piece(piece.bufferIndex, newStart, piece.end, this.getLineFeedCnt(piece.bufferIndex, newStart, piece.end), piece.length - 1);\n node.piece = nPiece;\n value += '\\n';\n updateTreeMetadata(this, node, -1, -1);\n if (node.piece.length === 0) {\n nodesToDel.push(node);\n }\n }\n var newPieces = this.createNewPieces(value);\n var newNode = this.rbInsertLeft(node, newPieces[newPieces.length - 1]);\n for (var k = newPieces.length - 2; k >= 0; k--) {\n newNode = this.rbInsertLeft(newNode, newPieces[k]);\n }\n this.validateCRLFWithPrevNode(newNode);\n this.deleteNodes(nodesToDel);\n };\n PieceTreeBase.prototype.insertContentToNodeRight = function (value, node) {\n // we are inserting to the right of this node.\n if (this.adjustCarriageReturnFromNext(value, node)) {\n // move \\n to the new node.\n value += '\\n';\n }\n var newPieces = this.createNewPieces(value);\n var newNode = this.rbInsertRight(node, newPieces[0]);\n var tmpNode = newNode;\n for (var k = 1; k < newPieces.length; k++) {\n tmpNode = this.rbInsertRight(tmpNode, newPieces[k]);\n }\n this.validateCRLFWithPrevNode(newNode);\n };\n PieceTreeBase.prototype.positionInBuffer = function (node, remainder, ret) {\n var piece = node.piece;\n var bufferIndex = node.piece.bufferIndex;\n var lineStarts = this._buffers[bufferIndex].lineStarts;\n var startOffset = lineStarts[piece.start.line] + piece.start.column;\n var offset = startOffset + remainder;\n // binary search offset between startOffset and endOffset\n var low = piece.start.line;\n var high = piece.end.line;\n var mid = 0;\n var midStop = 0;\n var midStart = 0;\n while (low <= high) {\n mid = low + ((high - low) / 2) | 0;\n midStart = lineStarts[mid];\n if (mid === high) {\n break;\n }\n midStop = lineStarts[mid + 1];\n if (offset < midStart) {\n high = mid - 1;\n }\n else if (offset >= midStop) {\n low = mid + 1;\n }\n else {\n break;\n }\n }\n if (ret) {\n ret.line = mid;\n ret.column = offset - midStart;\n return null;\n }\n return {\n line: mid,\n column: offset - midStart\n };\n };\n PieceTreeBase.prototype.getLineFeedCnt = function (bufferIndex, start, end) {\n // we don't need to worry about start: abc\\r|\\n, or abc|\\r, or abc|\\n, or abc|\\r\\n doesn't change the fact that, there is one line break after start.\n // now let's take care of end: abc\\r|\\n, if end is in between \\r and \\n, we need to add line feed count by 1\n if (end.column === 0) {\n return end.line - start.line;\n }\n var lineStarts = this._buffers[bufferIndex].lineStarts;\n if (end.line === lineStarts.length - 1) { // it means, there is no \\n after end, otherwise, there will be one more lineStart.\n return end.line - start.line;\n }\n var nextLineStartOffset = lineStarts[end.line + 1];\n var endOffset = lineStarts[end.line] + end.column;\n if (nextLineStartOffset > endOffset + 1) { // there are more than 1 character after end, which means it can't be \\n\n return end.line - start.line;\n }\n // endOffset + 1 === nextLineStartOffset\n // character at endOffset is \\n, so we check the character before first\n // if character at endOffset is \\r, end.column is 0 and we can't get here.\n var previousCharOffset = endOffset - 1; // end.column > 0 so it's okay.\n var buffer = this._buffers[bufferIndex].buffer;\n if (buffer.charCodeAt(previousCharOffset) === 13) {\n return end.line - start.line + 1;\n }\n else {\n return end.line - start.line;\n }\n };\n PieceTreeBase.prototype.offsetInBuffer = function (bufferIndex, cursor) {\n var lineStarts = this._buffers[bufferIndex].lineStarts;\n return lineStarts[cursor.line] + cursor.column;\n };\n PieceTreeBase.prototype.deleteNodes = function (nodes) {\n for (var i = 0; i < nodes.length; i++) {\n rbDelete(this, nodes[i]);\n }\n };\n PieceTreeBase.prototype.createNewPieces = function (text) {\n if (text.length > AverageBufferSize) {\n // the content is large, operations like substring, charCode becomes slow\n // so here we split it into smaller chunks, just like what we did for CR/LF normalization\n var newPieces = [];\n while (text.length > AverageBufferSize) {\n var lastChar = text.charCodeAt(AverageBufferSize - 1);\n var splitText = void 0;\n if (lastChar === 13 /* CarriageReturn */ || (lastChar >= 0xD800 && lastChar <= 0xDBFF)) {\n // last character is \\r or a high surrogate => keep it back\n splitText = text.substring(0, AverageBufferSize - 1);\n text = text.substring(AverageBufferSize - 1);\n }\n else {\n splitText = text.substring(0, AverageBufferSize);\n text = text.substring(AverageBufferSize);\n }\n var lineStarts_1 = createLineStartsFast(splitText);\n newPieces.push(new Piece(this._buffers.length, /* buffer index */ { line: 0, column: 0 }, { line: lineStarts_1.length - 1, column: splitText.length - lineStarts_1[lineStarts_1.length - 1] }, lineStarts_1.length - 1, splitText.length));\n this._buffers.push(new StringBuffer(splitText, lineStarts_1));\n }\n var lineStarts_2 = createLineStartsFast(text);\n newPieces.push(new Piece(this._buffers.length, /* buffer index */ { line: 0, column: 0 }, { line: lineStarts_2.length - 1, column: text.length - lineStarts_2[lineStarts_2.length - 1] }, lineStarts_2.length - 1, text.length));\n this._buffers.push(new StringBuffer(text, lineStarts_2));\n return newPieces;\n }\n var startOffset = this._buffers[0].buffer.length;\n var lineStarts = createLineStartsFast(text, false);\n var start = this._lastChangeBufferPos;\n if (this._buffers[0].lineStarts[this._buffers[0].lineStarts.length - 1] === startOffset\n && startOffset !== 0\n && this.startWithLF(text)\n && this.endWithCR(this._buffers[0].buffer) // todo, we can check this._lastChangeBufferPos's column as it's the last one\n ) {\n this._lastChangeBufferPos = { line: this._lastChangeBufferPos.line, column: this._lastChangeBufferPos.column + 1 };\n start = this._lastChangeBufferPos;\n for (var i = 0; i < lineStarts.length; i++) {\n lineStarts[i] += startOffset + 1;\n }\n this._buffers[0].lineStarts = this._buffers[0].lineStarts.concat(lineStarts.slice(1));\n this._buffers[0].buffer += '_' + text;\n startOffset += 1;\n }\n else {\n if (startOffset !== 0) {\n for (var i = 0; i < lineStarts.length; i++) {\n lineStarts[i] += startOffset;\n }\n }\n this._buffers[0].lineStarts = this._buffers[0].lineStarts.concat(lineStarts.slice(1));\n this._buffers[0].buffer += text;\n }\n var endOffset = this._buffers[0].buffer.length;\n var endIndex = this._buffers[0].lineStarts.length - 1;\n var endColumn = endOffset - this._buffers[0].lineStarts[endIndex];\n var endPos = { line: endIndex, column: endColumn };\n var newPiece = new Piece(0, /** todo@peng */ start, endPos, this.getLineFeedCnt(0, start, endPos), endOffset - startOffset);\n this._lastChangeBufferPos = endPos;\n return [newPiece];\n };\n PieceTreeBase.prototype.getLineRawContent = function (lineNumber, endOffset) {\n if (endOffset === void 0) { endOffset = 0; }\n var x = this.root;\n var ret = '';\n var cache = this._searchCache.get2(lineNumber);\n if (cache) {\n x = cache.node;\n var prevAccumualtedValue = this.getAccumulatedValue(x, lineNumber - cache.nodeStartLineNumber - 1);\n var buffer = this._buffers[x.piece.bufferIndex].buffer;\n var startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start);\n if (cache.nodeStartLineNumber + x.piece.lineFeedCnt === lineNumber) {\n ret = buffer.substring(startOffset + prevAccumualtedValue, startOffset + x.piece.length);\n }\n else {\n var accumualtedValue = this.getAccumulatedValue(x, lineNumber - cache.nodeStartLineNumber);\n return buffer.substring(startOffset + prevAccumualtedValue, startOffset + accumualtedValue - endOffset);\n }\n }\n else {\n var nodeStartOffset = 0;\n var originalLineNumber = lineNumber;\n while (x !== SENTINEL) {\n if (x.left !== SENTINEL && x.lf_left >= lineNumber - 1) {\n x = x.left;\n }\n else if (x.lf_left + x.piece.lineFeedCnt > lineNumber - 1) {\n var prevAccumualtedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 2);\n var accumualtedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 1);\n var buffer = this._buffers[x.piece.bufferIndex].buffer;\n var startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start);\n nodeStartOffset += x.size_left;\n this._searchCache.set({\n node: x,\n nodeStartOffset: nodeStartOffset,\n nodeStartLineNumber: originalLineNumber - (lineNumber - 1 - x.lf_left)\n });\n return buffer.substring(startOffset + prevAccumualtedValue, startOffset + accumualtedValue - endOffset);\n }\n else if (x.lf_left + x.piece.lineFeedCnt === lineNumber - 1) {\n var prevAccumualtedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 2);\n var buffer = this._buffers[x.piece.bufferIndex].buffer;\n var startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start);\n ret = buffer.substring(startOffset + prevAccumualtedValue, startOffset + x.piece.length);\n break;\n }\n else {\n lineNumber -= x.lf_left + x.piece.lineFeedCnt;\n nodeStartOffset += x.size_left + x.piece.length;\n x = x.right;\n }\n }\n }\n // search in order, to find the node contains end column\n x = x.next();\n while (x !== SENTINEL) {\n var buffer = this._buffers[x.piece.bufferIndex].buffer;\n if (x.piece.lineFeedCnt > 0) {\n var accumualtedValue = this.getAccumulatedValue(x, 0);\n var startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start);\n ret += buffer.substring(startOffset, startOffset + accumualtedValue - endOffset);\n return ret;\n }\n else {\n var startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start);\n ret += buffer.substr(startOffset, x.piece.length);\n }\n x = x.next();\n }\n return ret;\n };\n PieceTreeBase.prototype.computeBufferMetadata = function () {\n var x = this.root;\n var lfCnt = 1;\n var len = 0;\n while (x !== SENTINEL) {\n lfCnt += x.lf_left + x.piece.lineFeedCnt;\n len += x.size_left + x.piece.length;\n x = x.right;\n }\n this._lineCnt = lfCnt;\n this._length = len;\n this._searchCache.valdiate(this._length);\n };\n // #region node operations\n PieceTreeBase.prototype.getIndexOf = function (node, accumulatedValue) {\n var piece = node.piece;\n var pos = this.positionInBuffer(node, accumulatedValue);\n var lineCnt = pos.line - piece.start.line;\n if (this.offsetInBuffer(piece.bufferIndex, piece.end) - this.offsetInBuffer(piece.bufferIndex, piece.start) === accumulatedValue) {\n // we are checking the end of this node, so a CRLF check is necessary.\n var realLineCnt = this.getLineFeedCnt(node.piece.bufferIndex, piece.start, pos);\n if (realLineCnt !== lineCnt) {\n // aha yes, CRLF\n return { index: realLineCnt, remainder: 0 };\n }\n }\n return { index: lineCnt, remainder: pos.column };\n };\n PieceTreeBase.prototype.getAccumulatedValue = function (node, index) {\n if (index < 0) {\n return 0;\n }\n var piece = node.piece;\n var lineStarts = this._buffers[piece.bufferIndex].lineStarts;\n var expectedLineStartIndex = piece.start.line + index + 1;\n if (expectedLineStartIndex > piece.end.line) {\n return lineStarts[piece.end.line] + piece.end.column - lineStarts[piece.start.line] - piece.start.column;\n }\n else {\n return lineStarts[expectedLineStartIndex] - lineStarts[piece.start.line] - piece.start.column;\n }\n };\n PieceTreeBase.prototype.deleteNodeTail = function (node, pos) {\n var piece = node.piece;\n var originalLFCnt = piece.lineFeedCnt;\n var originalEndOffset = this.offsetInBuffer(piece.bufferIndex, piece.end);\n var newEnd = pos;\n var newEndOffset = this.offsetInBuffer(piece.bufferIndex, newEnd);\n var newLineFeedCnt = this.getLineFeedCnt(piece.bufferIndex, piece.start, newEnd);\n var lf_delta = newLineFeedCnt - originalLFCnt;\n var size_delta = newEndOffset - originalEndOffset;\n var newLength = piece.length + size_delta;\n node.piece = new Piece(piece.bufferIndex, piece.start, newEnd, newLineFeedCnt, newLength);\n updateTreeMetadata(this, node, size_delta, lf_delta);\n };\n PieceTreeBase.prototype.deleteNodeHead = function (node, pos) {\n var piece = node.piece;\n var originalLFCnt = piece.lineFeedCnt;\n var originalStartOffset = this.offsetInBuffer(piece.bufferIndex, piece.start);\n var newStart = pos;\n var newLineFeedCnt = this.getLineFeedCnt(piece.bufferIndex, newStart, piece.end);\n var newStartOffset = this.offsetInBuffer(piece.bufferIndex, newStart);\n var lf_delta = newLineFeedCnt - originalLFCnt;\n var size_delta = originalStartOffset - newStartOffset;\n var newLength = piece.length + size_delta;\n node.piece = new Piece(piece.bufferIndex, newStart, piece.end, newLineFeedCnt, newLength);\n updateTreeMetadata(this, node, size_delta, lf_delta);\n };\n PieceTreeBase.prototype.shrinkNode = function (node, start, end) {\n var piece = node.piece;\n var originalStartPos = piece.start;\n var originalEndPos = piece.end;\n // old piece, originalStartPos, start\n var oldLength = piece.length;\n var oldLFCnt = piece.lineFeedCnt;\n var newEnd = start;\n var newLineFeedCnt = this.getLineFeedCnt(piece.bufferIndex, piece.start, newEnd);\n var newLength = this.offsetInBuffer(piece.bufferIndex, start) - this.offsetInBuffer(piece.bufferIndex, originalStartPos);\n node.piece = new Piece(piece.bufferIndex, piece.start, newEnd, newLineFeedCnt, newLength);\n updateTreeMetadata(this, node, newLength - oldLength, newLineFeedCnt - oldLFCnt);\n // new right piece, end, originalEndPos\n var newPiece = new Piece(piece.bufferIndex, end, originalEndPos, this.getLineFeedCnt(piece.bufferIndex, end, originalEndPos), this.offsetInBuffer(piece.bufferIndex, originalEndPos) - this.offsetInBuffer(piece.bufferIndex, end));\n var newNode = this.rbInsertRight(node, newPiece);\n this.validateCRLFWithPrevNode(newNode);\n };\n PieceTreeBase.prototype.appendToNode = function (node, value) {\n if (this.adjustCarriageReturnFromNext(value, node)) {\n value += '\\n';\n }\n var hitCRLF = this.shouldCheckCRLF() && this.startWithLF(value) && this.endWithCR(node);\n var startOffset = this._buffers[0].buffer.length;\n this._buffers[0].buffer += value;\n var lineStarts = createLineStartsFast(value, false);\n for (var i = 0; i < lineStarts.length; i++) {\n lineStarts[i] += startOffset;\n }\n if (hitCRLF) {\n var prevStartOffset = this._buffers[0].lineStarts[this._buffers[0].lineStarts.length - 2];\n this._buffers[0].lineStarts.pop();\n // _lastChangeBufferPos is already wrong\n this._lastChangeBufferPos = { line: this._lastChangeBufferPos.line - 1, column: startOffset - prevStartOffset };\n }\n this._buffers[0].lineStarts = this._buffers[0].lineStarts.concat(lineStarts.slice(1));\n var endIndex = this._buffers[0].lineStarts.length - 1;\n var endColumn = this._buffers[0].buffer.length - this._buffers[0].lineStarts[endIndex];\n var newEnd = { line: endIndex, column: endColumn };\n var newLength = node.piece.length + value.length;\n var oldLineFeedCnt = node.piece.lineFeedCnt;\n var newLineFeedCnt = this.getLineFeedCnt(0, node.piece.start, newEnd);\n var lf_delta = newLineFeedCnt - oldLineFeedCnt;\n node.piece = new Piece(node.piece.bufferIndex, node.piece.start, newEnd, newLineFeedCnt, newLength);\n this._lastChangeBufferPos = newEnd;\n updateTreeMetadata(this, node, value.length, lf_delta);\n };\n PieceTreeBase.prototype.nodeAt = function (offset) {\n var x = this.root;\n var cache = this._searchCache.get(offset);\n if (cache) {\n return {\n node: cache.node,\n nodeStartOffset: cache.nodeStartOffset,\n remainder: offset - cache.nodeStartOffset\n };\n }\n var nodeStartOffset = 0;\n while (x !== SENTINEL) {\n if (x.size_left > offset) {\n x = x.left;\n }\n else if (x.size_left + x.piece.length >= offset) {\n nodeStartOffset += x.size_left;\n var ret = {\n node: x,\n remainder: offset - x.size_left,\n nodeStartOffset: nodeStartOffset\n };\n this._searchCache.set(ret);\n return ret;\n }\n else {\n offset -= x.size_left + x.piece.length;\n nodeStartOffset += x.size_left + x.piece.length;\n x = x.right;\n }\n }\n return null;\n };\n PieceTreeBase.prototype.nodeAt2 = function (lineNumber, column) {\n var x = this.root;\n var nodeStartOffset = 0;\n while (x !== SENTINEL) {\n if (x.left !== SENTINEL && x.lf_left >= lineNumber - 1) {\n x = x.left;\n }\n else if (x.lf_left + x.piece.lineFeedCnt > lineNumber - 1) {\n var prevAccumualtedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 2);\n var accumualtedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 1);\n nodeStartOffset += x.size_left;\n return {\n node: x,\n remainder: Math.min(prevAccumualtedValue + column - 1, accumualtedValue),\n nodeStartOffset: nodeStartOffset\n };\n }\n else if (x.lf_left + x.piece.lineFeedCnt === lineNumber - 1) {\n var prevAccumualtedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 2);\n if (prevAccumualtedValue + column - 1 <= x.piece.length) {\n return {\n node: x,\n remainder: prevAccumualtedValue + column - 1,\n nodeStartOffset: nodeStartOffset\n };\n }\n else {\n column -= x.piece.length - prevAccumualtedValue;\n break;\n }\n }\n else {\n lineNumber -= x.lf_left + x.piece.lineFeedCnt;\n nodeStartOffset += x.size_left + x.piece.length;\n x = x.right;\n }\n }\n // search in order, to find the node contains position.column\n x = x.next();\n while (x !== SENTINEL) {\n if (x.piece.lineFeedCnt > 0) {\n var accumualtedValue = this.getAccumulatedValue(x, 0);\n var nodeStartOffset_1 = this.offsetOfNode(x);\n return {\n node: x,\n remainder: Math.min(column - 1, accumualtedValue),\n nodeStartOffset: nodeStartOffset_1\n };\n }\n else {\n if (x.piece.length >= column - 1) {\n var nodeStartOffset_2 = this.offsetOfNode(x);\n return {\n node: x,\n remainder: column - 1,\n nodeStartOffset: nodeStartOffset_2\n };\n }\n else {\n column -= x.piece.length;\n }\n }\n x = x.next();\n }\n return null;\n };\n PieceTreeBase.prototype.nodeCharCodeAt = function (node, offset) {\n if (node.piece.lineFeedCnt < 1) {\n return -1;\n }\n var buffer = this._buffers[node.piece.bufferIndex];\n var newOffset = this.offsetInBuffer(node.piece.bufferIndex, node.piece.start) + offset;\n return buffer.buffer.charCodeAt(newOffset);\n };\n PieceTreeBase.prototype.offsetOfNode = function (node) {\n if (!node) {\n return 0;\n }\n var pos = node.size_left;\n while (node !== this.root) {\n if (node.parent.right === node) {\n pos += node.parent.size_left + node.parent.piece.length;\n }\n node = node.parent;\n }\n return pos;\n };\n // #endregion\n // #region CRLF\n PieceTreeBase.prototype.shouldCheckCRLF = function () {\n return !(this._EOLNormalized && this._EOL === '\\n');\n };\n PieceTreeBase.prototype.startWithLF = function (val) {\n if (typeof val === 'string') {\n return val.charCodeAt(0) === 10;\n }\n if (val === SENTINEL || val.piece.lineFeedCnt === 0) {\n return false;\n }\n var piece = val.piece;\n var lineStarts = this._buffers[piece.bufferIndex].lineStarts;\n var line = piece.start.line;\n var startOffset = lineStarts[line] + piece.start.column;\n if (line === lineStarts.length - 1) {\n // last line, so there is no line feed at the end of this line\n return false;\n }\n var nextLineOffset = lineStarts[line + 1];\n if (nextLineOffset > startOffset + 1) {\n return false;\n }\n return this._buffers[piece.bufferIndex].buffer.charCodeAt(startOffset) === 10;\n };\n PieceTreeBase.prototype.endWithCR = function (val) {\n if (typeof val === 'string') {\n return val.charCodeAt(val.length - 1) === 13;\n }\n if (val === SENTINEL || val.piece.lineFeedCnt === 0) {\n return false;\n }\n return this.nodeCharCodeAt(val, val.piece.length - 1) === 13;\n };\n PieceTreeBase.prototype.validateCRLFWithPrevNode = function (nextNode) {\n if (this.shouldCheckCRLF() && this.startWithLF(nextNode)) {\n var node = nextNode.prev();\n if (this.endWithCR(node)) {\n this.fixCRLF(node, nextNode);\n }\n }\n };\n PieceTreeBase.prototype.validateCRLFWithNextNode = function (node) {\n if (this.shouldCheckCRLF() && this.endWithCR(node)) {\n var nextNode = node.next();\n if (this.startWithLF(nextNode)) {\n this.fixCRLF(node, nextNode);\n }\n }\n };\n PieceTreeBase.prototype.fixCRLF = function (prev, next) {\n var nodesToDel = [];\n // update node\n var lineStarts = this._buffers[prev.piece.bufferIndex].lineStarts;\n var newEnd;\n if (prev.piece.end.column === 0) {\n // it means, last line ends with \\r, not \\r\\n\n newEnd = { line: prev.piece.end.line - 1, column: lineStarts[prev.piece.end.line] - lineStarts[prev.piece.end.line - 1] - 1 };\n }\n else {\n // \\r\\n\n newEnd = { line: prev.piece.end.line, column: prev.piece.end.column - 1 };\n }\n var prevNewLength = prev.piece.length - 1;\n var prevNewLFCnt = prev.piece.lineFeedCnt - 1;\n prev.piece = new Piece(prev.piece.bufferIndex, prev.piece.start, newEnd, prevNewLFCnt, prevNewLength);\n updateTreeMetadata(this, prev, -1, -1);\n if (prev.piece.length === 0) {\n nodesToDel.push(prev);\n }\n // update nextNode\n var newStart = { line: next.piece.start.line + 1, column: 0 };\n var newLength = next.piece.length - 1;\n var newLineFeedCnt = this.getLineFeedCnt(next.piece.bufferIndex, newStart, next.piece.end);\n next.piece = new Piece(next.piece.bufferIndex, newStart, next.piece.end, newLineFeedCnt, newLength);\n updateTreeMetadata(this, next, -1, -1);\n if (next.piece.length === 0) {\n nodesToDel.push(next);\n }\n // create new piece which contains \\r\\n\n var pieces = this.createNewPieces('\\r\\n');\n this.rbInsertRight(prev, pieces[0]);\n // delete empty nodes\n for (var i = 0; i < nodesToDel.length; i++) {\n rbDelete(this, nodesToDel[i]);\n }\n };\n PieceTreeBase.prototype.adjustCarriageReturnFromNext = function (value, node) {\n if (this.shouldCheckCRLF() && this.endWithCR(value)) {\n var nextNode = node.next();\n if (this.startWithLF(nextNode)) {\n // move `\\n` forward\n value += '\\n';\n if (nextNode.piece.length === 1) {\n rbDelete(this, nextNode);\n }\n else {\n var piece = nextNode.piece;\n var newStart = { line: piece.start.line + 1, column: 0 };\n var newLength = piece.length - 1;\n var newLineFeedCnt = this.getLineFeedCnt(piece.bufferIndex, newStart, piece.end);\n nextNode.piece = new Piece(piece.bufferIndex, newStart, piece.end, newLineFeedCnt, newLength);\n updateTreeMetadata(this, nextNode, -1, -1);\n }\n return true;\n }\n }\n return false;\n };\n // #endregion\n // #endregion\n // #region Tree operations\n PieceTreeBase.prototype.iterate = function (node, callback) {\n if (node === SENTINEL) {\n return callback(SENTINEL);\n }\n var leftRet = this.iterate(node.left, callback);\n if (!leftRet) {\n return leftRet;\n }\n return callback(node) && this.iterate(node.right, callback);\n };\n PieceTreeBase.prototype.getNodeContent = function (node) {\n if (node === SENTINEL) {\n return '';\n }\n var buffer = this._buffers[node.piece.bufferIndex];\n var currentContent;\n var piece = node.piece;\n var startOffset = this.offsetInBuffer(piece.bufferIndex, piece.start);\n var endOffset = this.offsetInBuffer(piece.bufferIndex, piece.end);\n currentContent = buffer.buffer.substring(startOffset, endOffset);\n return currentContent;\n };\n /**\n * node node\n * / \\ / \\\n * a b <---- a b\n * /\n * z\n */\n PieceTreeBase.prototype.rbInsertRight = function (node, p) {\n var z = new TreeNode(p, 1 /* Red */);\n z.left = SENTINEL;\n z.right = SENTINEL;\n z.parent = SENTINEL;\n z.size_left = 0;\n z.lf_left = 0;\n var x = this.root;\n if (x === SENTINEL) {\n this.root = z;\n z.color = 0 /* Black */;\n }\n else if (node.right === SENTINEL) {\n node.right = z;\n z.parent = node;\n }\n else {\n var nextNode = leftest(node.right);\n nextNode.left = z;\n z.parent = nextNode;\n }\n fixInsert(this, z);\n return z;\n };\n /**\n * node node\n * / \\ / \\\n * a b ----> a b\n * \\\n * z\n */\n PieceTreeBase.prototype.rbInsertLeft = function (node, p) {\n var z = new TreeNode(p, 1 /* Red */);\n z.left = SENTINEL;\n z.right = SENTINEL;\n z.parent = SENTINEL;\n z.size_left = 0;\n z.lf_left = 0;\n if (this.root === SENTINEL) {\n this.root = z;\n z.color = 0 /* Black */;\n }\n else if (node.left === SENTINEL) {\n node.left = z;\n z.parent = node;\n }\n else {\n var prevNode = righttest(node.left); // a\n prevNode.right = z;\n z.parent = prevNode;\n }\n fixInsert(this, z);\n return z;\n };\n PieceTreeBase.prototype.getContentOfSubTree = function (node) {\n var _this = this;\n var str = '';\n this.iterate(node, function (node) {\n str += _this.getNodeContent(node);\n return true;\n });\n return str;\n };\n return PieceTreeBase;\n}());\nexport { PieceTreeBase };\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport * as strings from '../../../../base/common/strings.js';\nimport { Range } from '../../core/range.js';\nimport { ApplyEditsResult } from '../../model.js';\nimport { PieceTreeBase } from './pieceTreeBase.js';\nvar PieceTreeTextBuffer = /** @class */ (function () {\n function PieceTreeTextBuffer(chunks, BOM, eol, containsRTL, isBasicASCII, eolNormalized) {\n this._BOM = BOM;\n this._mightContainNonBasicASCII = !isBasicASCII;\n this._mightContainRTL = containsRTL;\n this._pieceTree = new PieceTreeBase(chunks, eol, eolNormalized);\n }\n PieceTreeTextBuffer.prototype.mightContainRTL = function () {\n return this._mightContainRTL;\n };\n PieceTreeTextBuffer.prototype.mightContainNonBasicASCII = function () {\n return this._mightContainNonBasicASCII;\n };\n PieceTreeTextBuffer.prototype.getBOM = function () {\n return this._BOM;\n };\n PieceTreeTextBuffer.prototype.getEOL = function () {\n return this._pieceTree.getEOL();\n };\n PieceTreeTextBuffer.prototype.getOffsetAt = function (lineNumber, column) {\n return this._pieceTree.getOffsetAt(lineNumber, column);\n };\n PieceTreeTextBuffer.prototype.getPositionAt = function (offset) {\n return this._pieceTree.getPositionAt(offset);\n };\n PieceTreeTextBuffer.prototype.getRangeAt = function (start, length) {\n var end = start + length;\n var startPosition = this.getPositionAt(start);\n var endPosition = this.getPositionAt(end);\n return new Range(startPosition.lineNumber, startPosition.column, endPosition.lineNumber, endPosition.column);\n };\n PieceTreeTextBuffer.prototype.getValueInRange = function (range, eol) {\n if (eol === void 0) { eol = 0 /* TextDefined */; }\n if (range.isEmpty()) {\n return '';\n }\n var lineEnding = this._getEndOfLine(eol);\n return this._pieceTree.getValueInRange(range, lineEnding);\n };\n PieceTreeTextBuffer.prototype.getValueLengthInRange = function (range, eol) {\n if (eol === void 0) { eol = 0 /* TextDefined */; }\n if (range.isEmpty()) {\n return 0;\n }\n if (range.startLineNumber === range.endLineNumber) {\n return (range.endColumn - range.startColumn);\n }\n var startOffset = this.getOffsetAt(range.startLineNumber, range.startColumn);\n var endOffset = this.getOffsetAt(range.endLineNumber, range.endColumn);\n return endOffset - startOffset;\n };\n PieceTreeTextBuffer.prototype.getLength = function () {\n return this._pieceTree.getLength();\n };\n PieceTreeTextBuffer.prototype.getLineCount = function () {\n return this._pieceTree.getLineCount();\n };\n PieceTreeTextBuffer.prototype.getLinesContent = function () {\n return this._pieceTree.getLinesContent();\n };\n PieceTreeTextBuffer.prototype.getLineContent = function (lineNumber) {\n return this._pieceTree.getLineContent(lineNumber);\n };\n PieceTreeTextBuffer.prototype.getLineCharCode = function (lineNumber, index) {\n return this._pieceTree.getLineCharCode(lineNumber, index);\n };\n PieceTreeTextBuffer.prototype.getLineLength = function (lineNumber) {\n return this._pieceTree.getLineLength(lineNumber);\n };\n PieceTreeTextBuffer.prototype.getLineFirstNonWhitespaceColumn = function (lineNumber) {\n var result = strings.firstNonWhitespaceIndex(this.getLineContent(lineNumber));\n if (result === -1) {\n return 0;\n }\n return result + 1;\n };\n PieceTreeTextBuffer.prototype.getLineLastNonWhitespaceColumn = function (lineNumber) {\n var result = strings.lastNonWhitespaceIndex(this.getLineContent(lineNumber));\n if (result === -1) {\n return 0;\n }\n return result + 2;\n };\n PieceTreeTextBuffer.prototype._getEndOfLine = function (eol) {\n switch (eol) {\n case 1 /* LF */:\n return '\\n';\n case 2 /* CRLF */:\n return '\\r\\n';\n case 0 /* TextDefined */:\n return this.getEOL();\n }\n throw new Error('Unknown EOL preference');\n };\n PieceTreeTextBuffer.prototype.setEOL = function (newEOL) {\n this._pieceTree.setEOL(newEOL);\n };\n PieceTreeTextBuffer.prototype.applyEdits = function (rawOperations, recordTrimAutoWhitespace) {\n var mightContainRTL = this._mightContainRTL;\n var mightContainNonBasicASCII = this._mightContainNonBasicASCII;\n var canReduceOperations = true;\n var operations = [];\n for (var i = 0; i < rawOperations.length; i++) {\n var op = rawOperations[i];\n if (canReduceOperations && op._isTracked) {\n canReduceOperations = false;\n }\n var validatedRange = op.range;\n if (!mightContainRTL && op.text) {\n // check if the new inserted text contains RTL\n mightContainRTL = strings.containsRTL(op.text);\n }\n if (!mightContainNonBasicASCII && op.text) {\n mightContainNonBasicASCII = !strings.isBasicASCII(op.text);\n }\n operations[i] = {\n sortIndex: i,\n identifier: op.identifier || null,\n range: validatedRange,\n rangeOffset: this.getOffsetAt(validatedRange.startLineNumber, validatedRange.startColumn),\n rangeLength: this.getValueLengthInRange(validatedRange),\n lines: op.text ? op.text.split(/\\r\\n|\\r|\\n/) : null,\n forceMoveMarkers: Boolean(op.forceMoveMarkers),\n isAutoWhitespaceEdit: op.isAutoWhitespaceEdit || false\n };\n }\n // Sort operations ascending\n operations.sort(PieceTreeTextBuffer._sortOpsAscending);\n var hasTouchingRanges = false;\n for (var i = 0, count = operations.length - 1; i < count; i++) {\n var rangeEnd = operations[i].range.getEndPosition();\n var nextRangeStart = operations[i + 1].range.getStartPosition();\n if (nextRangeStart.isBeforeOrEqual(rangeEnd)) {\n if (nextRangeStart.isBefore(rangeEnd)) {\n // overlapping ranges\n throw new Error('Overlapping ranges are not allowed!');\n }\n hasTouchingRanges = true;\n }\n }\n if (canReduceOperations) {\n operations = this._reduceOperations(operations);\n }\n // Delta encode operations\n var reverseRanges = PieceTreeTextBuffer._getInverseEditRanges(operations);\n var newTrimAutoWhitespaceCandidates = [];\n for (var i = 0; i < operations.length; i++) {\n var op = operations[i];\n var reverseRange = reverseRanges[i];\n if (recordTrimAutoWhitespace && op.isAutoWhitespaceEdit && op.range.isEmpty()) {\n // Record already the future line numbers that might be auto whitespace removal candidates on next edit\n for (var lineNumber = reverseRange.startLineNumber; lineNumber <= reverseRange.endLineNumber; lineNumber++) {\n var currentLineContent = '';\n if (lineNumber === reverseRange.startLineNumber) {\n currentLineContent = this.getLineContent(op.range.startLineNumber);\n if (strings.firstNonWhitespaceIndex(currentLineContent) !== -1) {\n continue;\n }\n }\n newTrimAutoWhitespaceCandidates.push({ lineNumber: lineNumber, oldContent: currentLineContent });\n }\n }\n }\n var reverseOperations = [];\n for (var i = 0; i < operations.length; i++) {\n var op = operations[i];\n var reverseRange = reverseRanges[i];\n reverseOperations[i] = {\n sortIndex: op.sortIndex,\n identifier: op.identifier,\n range: reverseRange,\n text: this.getValueInRange(op.range),\n forceMoveMarkers: op.forceMoveMarkers\n };\n }\n // Can only sort reverse operations when the order is not significant\n if (!hasTouchingRanges) {\n reverseOperations.sort(function (a, b) { return a.sortIndex - b.sortIndex; });\n }\n this._mightContainRTL = mightContainRTL;\n this._mightContainNonBasicASCII = mightContainNonBasicASCII;\n var contentChanges = this._doApplyEdits(operations);\n var trimAutoWhitespaceLineNumbers = null;\n if (recordTrimAutoWhitespace && newTrimAutoWhitespaceCandidates.length > 0) {\n // sort line numbers auto whitespace removal candidates for next edit descending\n newTrimAutoWhitespaceCandidates.sort(function (a, b) { return b.lineNumber - a.lineNumber; });\n trimAutoWhitespaceLineNumbers = [];\n for (var i = 0, len = newTrimAutoWhitespaceCandidates.length; i < len; i++) {\n var lineNumber = newTrimAutoWhitespaceCandidates[i].lineNumber;\n if (i > 0 && newTrimAutoWhitespaceCandidates[i - 1].lineNumber === lineNumber) {\n // Do not have the same line number twice\n continue;\n }\n var prevContent = newTrimAutoWhitespaceCandidates[i].oldContent;\n var lineContent = this.getLineContent(lineNumber);\n if (lineContent.length === 0 || lineContent === prevContent || strings.firstNonWhitespaceIndex(lineContent) !== -1) {\n continue;\n }\n trimAutoWhitespaceLineNumbers.push(lineNumber);\n }\n }\n return new ApplyEditsResult(reverseOperations, contentChanges, trimAutoWhitespaceLineNumbers);\n };\n /**\n * Transform operations such that they represent the same logic edit,\n * but that they also do not cause OOM crashes.\n */\n PieceTreeTextBuffer.prototype._reduceOperations = function (operations) {\n if (operations.length < 1000) {\n // We know from empirical testing that a thousand edits work fine regardless of their shape.\n return operations;\n }\n // At one point, due to how events are emitted and how each operation is handled,\n // some operations can trigger a high amount of temporary string allocations,\n // that will immediately get edited again.\n // e.g. a formatter inserting ridiculous ammounts of \\n on a model with a single line\n // Therefore, the strategy is to collapse all the operations into a huge single edit operation\n return [this._toSingleEditOperation(operations)];\n };\n PieceTreeTextBuffer.prototype._toSingleEditOperation = function (operations) {\n var forceMoveMarkers = false, firstEditRange = operations[0].range, lastEditRange = operations[operations.length - 1].range, entireEditRange = new Range(firstEditRange.startLineNumber, firstEditRange.startColumn, lastEditRange.endLineNumber, lastEditRange.endColumn), lastEndLineNumber = firstEditRange.startLineNumber, lastEndColumn = firstEditRange.startColumn, result = [];\n for (var i = 0, len = operations.length; i < len; i++) {\n var operation = operations[i], range = operation.range;\n forceMoveMarkers = forceMoveMarkers || operation.forceMoveMarkers;\n // (1) -- Push old text\n for (var lineNumber = lastEndLineNumber; lineNumber < range.startLineNumber; lineNumber++) {\n if (lineNumber === lastEndLineNumber) {\n result.push(this.getLineContent(lineNumber).substring(lastEndColumn - 1));\n }\n else {\n result.push('\\n');\n result.push(this.getLineContent(lineNumber));\n }\n }\n if (range.startLineNumber === lastEndLineNumber) {\n result.push(this.getLineContent(range.startLineNumber).substring(lastEndColumn - 1, range.startColumn - 1));\n }\n else {\n result.push('\\n');\n result.push(this.getLineContent(range.startLineNumber).substring(0, range.startColumn - 1));\n }\n // (2) -- Push new text\n if (operation.lines) {\n for (var j = 0, lenJ = operation.lines.length; j < lenJ; j++) {\n if (j !== 0) {\n result.push('\\n');\n }\n result.push(operation.lines[j]);\n }\n }\n lastEndLineNumber = operation.range.endLineNumber;\n lastEndColumn = operation.range.endColumn;\n }\n return {\n sortIndex: 0,\n identifier: operations[0].identifier,\n range: entireEditRange,\n rangeOffset: this.getOffsetAt(entireEditRange.startLineNumber, entireEditRange.startColumn),\n rangeLength: this.getValueLengthInRange(entireEditRange, 0 /* TextDefined */),\n lines: result.join('').split('\\n'),\n forceMoveMarkers: forceMoveMarkers,\n isAutoWhitespaceEdit: false\n };\n };\n PieceTreeTextBuffer.prototype._doApplyEdits = function (operations) {\n operations.sort(PieceTreeTextBuffer._sortOpsDescending);\n var contentChanges = [];\n // operations are from bottom to top\n for (var i = 0; i < operations.length; i++) {\n var op = operations[i];\n var startLineNumber = op.range.startLineNumber;\n var startColumn = op.range.startColumn;\n var endLineNumber = op.range.endLineNumber;\n var endColumn = op.range.endColumn;\n if (startLineNumber === endLineNumber && startColumn === endColumn && (!op.lines || op.lines.length === 0)) {\n // no-op\n continue;\n }\n var deletingLinesCnt = endLineNumber - startLineNumber;\n var insertingLinesCnt = (op.lines ? op.lines.length - 1 : 0);\n var editingLinesCnt = Math.min(deletingLinesCnt, insertingLinesCnt);\n var text = (op.lines ? op.lines.join(this.getEOL()) : '');\n if (text) {\n // replacement\n this._pieceTree.delete(op.rangeOffset, op.rangeLength);\n this._pieceTree.insert(op.rangeOffset, text, true);\n }\n else {\n // deletion\n this._pieceTree.delete(op.rangeOffset, op.rangeLength);\n }\n if (editingLinesCnt < insertingLinesCnt) {\n var newLinesContent = [];\n for (var j = editingLinesCnt + 1; j <= insertingLinesCnt; j++) {\n newLinesContent.push(op.lines[j]);\n }\n newLinesContent[newLinesContent.length - 1] = this.getLineContent(startLineNumber + insertingLinesCnt - 1);\n }\n var contentChangeRange = new Range(startLineNumber, startColumn, endLineNumber, endColumn);\n contentChanges.push({\n range: contentChangeRange,\n rangeLength: op.rangeLength,\n text: text,\n rangeOffset: op.rangeOffset,\n forceMoveMarkers: op.forceMoveMarkers\n });\n }\n return contentChanges;\n };\n PieceTreeTextBuffer.prototype.findMatchesLineByLine = function (searchRange, searchData, captureMatches, limitResultCount) {\n return this._pieceTree.findMatchesLineByLine(searchRange, searchData, captureMatches, limitResultCount);\n };\n /**\n * Assumes `operations` are validated and sorted ascending\n */\n PieceTreeTextBuffer._getInverseEditRanges = function (operations) {\n var result = [];\n var prevOpEndLineNumber = 0;\n var prevOpEndColumn = 0;\n var prevOp = null;\n for (var i = 0, len = operations.length; i < len; i++) {\n var op = operations[i];\n var startLineNumber = void 0;\n var startColumn = void 0;\n if (prevOp) {\n if (prevOp.range.endLineNumber === op.range.startLineNumber) {\n startLineNumber = prevOpEndLineNumber;\n startColumn = prevOpEndColumn + (op.range.startColumn - prevOp.range.endColumn);\n }\n else {\n startLineNumber = prevOpEndLineNumber + (op.range.startLineNumber - prevOp.range.endLineNumber);\n startColumn = op.range.startColumn;\n }\n }\n else {\n startLineNumber = op.range.startLineNumber;\n startColumn = op.range.startColumn;\n }\n var resultRange = void 0;\n if (op.lines && op.lines.length > 0) {\n // the operation inserts something\n var lineCount = op.lines.length;\n var firstLine = op.lines[0];\n var lastLine = op.lines[lineCount - 1];\n if (lineCount === 1) {\n // single line insert\n resultRange = new Range(startLineNumber, startColumn, startLineNumber, startColumn + firstLine.length);\n }\n else {\n // multi line insert\n resultRange = new Range(startLineNumber, startColumn, startLineNumber + lineCount - 1, lastLine.length + 1);\n }\n }\n else {\n // There is nothing to insert\n resultRange = new Range(startLineNumber, startColumn, startLineNumber, startColumn);\n }\n prevOpEndLineNumber = resultRange.endLineNumber;\n prevOpEndColumn = resultRange.endColumn;\n result.push(resultRange);\n prevOp = op;\n }\n return result;\n };\n PieceTreeTextBuffer._sortOpsAscending = function (a, b) {\n var r = Range.compareRangesUsingEnds(a.range, b.range);\n if (r === 0) {\n return a.sortIndex - b.sortIndex;\n }\n return r;\n };\n PieceTreeTextBuffer._sortOpsDescending = function (a, b) {\n var r = Range.compareRangesUsingEnds(a.range, b.range);\n if (r === 0) {\n return b.sortIndex - a.sortIndex;\n }\n return -r;\n };\n return PieceTreeTextBuffer;\n}());\nexport { PieceTreeTextBuffer };\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport * as strings from '../../../../base/common/strings.js';\nimport { StringBuffer, createLineStarts, createLineStartsFast } from './pieceTreeBase.js';\nimport { PieceTreeTextBuffer } from './pieceTreeTextBuffer.js';\nvar PieceTreeTextBufferFactory = /** @class */ (function () {\n function PieceTreeTextBufferFactory(_chunks, _bom, _cr, _lf, _crlf, _containsRTL, _isBasicASCII, _normalizeEOL) {\n this._chunks = _chunks;\n this._bom = _bom;\n this._cr = _cr;\n this._lf = _lf;\n this._crlf = _crlf;\n this._containsRTL = _containsRTL;\n this._isBasicASCII = _isBasicASCII;\n this._normalizeEOL = _normalizeEOL;\n }\n PieceTreeTextBufferFactory.prototype._getEOL = function (defaultEOL) {\n var totalEOLCount = this._cr + this._lf + this._crlf;\n var totalCRCount = this._cr + this._crlf;\n if (totalEOLCount === 0) {\n // This is an empty file or a file with precisely one line\n return (defaultEOL === 1 /* LF */ ? '\\n' : '\\r\\n');\n }\n if (totalCRCount > totalEOLCount / 2) {\n // More than half of the file contains \\r\\n ending lines\n return '\\r\\n';\n }\n // At least one line more ends in \\n\n return '\\n';\n };\n PieceTreeTextBufferFactory.prototype.create = function (defaultEOL) {\n var eol = this._getEOL(defaultEOL);\n var chunks = this._chunks;\n if (this._normalizeEOL &&\n ((eol === '\\r\\n' && (this._cr > 0 || this._lf > 0))\n || (eol === '\\n' && (this._cr > 0 || this._crlf > 0)))) {\n // Normalize pieces\n for (var i = 0, len = chunks.length; i < len; i++) {\n var str = chunks[i].buffer.replace(/\\r\\n|\\r|\\n/g, eol);\n var newLineStart = createLineStartsFast(str);\n chunks[i] = new StringBuffer(str, newLineStart);\n }\n }\n return new PieceTreeTextBuffer(chunks, this._bom, eol, this._containsRTL, this._isBasicASCII, this._normalizeEOL);\n };\n return PieceTreeTextBufferFactory;\n}());\nexport { PieceTreeTextBufferFactory };\nvar PieceTreeTextBufferBuilder = /** @class */ (function () {\n function PieceTreeTextBufferBuilder() {\n this.chunks = [];\n this.BOM = '';\n this._hasPreviousChar = false;\n this._previousChar = 0;\n this._tmpLineStarts = [];\n this.cr = 0;\n this.lf = 0;\n this.crlf = 0;\n this.containsRTL = false;\n this.isBasicASCII = true;\n }\n PieceTreeTextBufferBuilder.prototype.acceptChunk = function (chunk) {\n if (chunk.length === 0) {\n return;\n }\n if (this.chunks.length === 0) {\n if (strings.startsWithUTF8BOM(chunk)) {\n this.BOM = strings.UTF8_BOM_CHARACTER;\n chunk = chunk.substr(1);\n }\n }\n var lastChar = chunk.charCodeAt(chunk.length - 1);\n if (lastChar === 13 /* CarriageReturn */ || (lastChar >= 0xD800 && lastChar <= 0xDBFF)) {\n // last character is \\r or a high surrogate => keep it back\n this._acceptChunk1(chunk.substr(0, chunk.length - 1), false);\n this._hasPreviousChar = true;\n this._previousChar = lastChar;\n }\n else {\n this._acceptChunk1(chunk, false);\n this._hasPreviousChar = false;\n this._previousChar = lastChar;\n }\n };\n PieceTreeTextBufferBuilder.prototype._acceptChunk1 = function (chunk, allowEmptyStrings) {\n if (!allowEmptyStrings && chunk.length === 0) {\n // Nothing to do\n return;\n }\n if (this._hasPreviousChar) {\n this._acceptChunk2(String.fromCharCode(this._previousChar) + chunk);\n }\n else {\n this._acceptChunk2(chunk);\n }\n };\n PieceTreeTextBufferBuilder.prototype._acceptChunk2 = function (chunk) {\n var lineStarts = createLineStarts(this._tmpLineStarts, chunk);\n this.chunks.push(new StringBuffer(chunk, lineStarts.lineStarts));\n this.cr += lineStarts.cr;\n this.lf += lineStarts.lf;\n this.crlf += lineStarts.crlf;\n if (this.isBasicASCII) {\n this.isBasicASCII = lineStarts.isBasicASCII;\n }\n if (!this.isBasicASCII && !this.containsRTL) {\n // No need to check if is basic ASCII\n this.containsRTL = strings.containsRTL(chunk);\n }\n };\n PieceTreeTextBufferBuilder.prototype.finish = function (normalizeEOL) {\n if (normalizeEOL === void 0) { normalizeEOL = true; }\n this._finish();\n return new PieceTreeTextBufferFactory(this.chunks, this.BOM, this.cr, this.lf, this.crlf, this.containsRTL, this.isBasicASCII, normalizeEOL);\n };\n PieceTreeTextBufferBuilder.prototype._finish = function () {\n if (this.chunks.length === 0) {\n this._acceptChunk1('', true);\n }\n if (this._hasPreviousChar) {\n this._hasPreviousChar = false;\n // recreate last chunk\n var lastChunk = this.chunks[this.chunks.length - 1];\n lastChunk.buffer += String.fromCharCode(this._previousChar);\n var newLineStarts = createLineStartsFast(lastChunk.buffer);\n lastChunk.lineStarts = newLineStarts;\n if (this._previousChar === 13 /* CarriageReturn */) {\n this.cr++;\n }\n }\n };\n return PieceTreeTextBufferBuilder;\n}());\nexport { PieceTreeTextBufferBuilder };\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n/**\n * An event describing that a model has been reset to a new value.\n * @internal\n */\nvar ModelRawFlush = /** @class */ (function () {\n function ModelRawFlush() {\n this.changeType = 1 /* Flush */;\n }\n return ModelRawFlush;\n}());\nexport { ModelRawFlush };\n/**\n * An event describing that a line has changed in a model.\n * @internal\n */\nvar ModelRawLineChanged = /** @class */ (function () {\n function ModelRawLineChanged(lineNumber, detail) {\n this.changeType = 2 /* LineChanged */;\n this.lineNumber = lineNumber;\n this.detail = detail;\n }\n return ModelRawLineChanged;\n}());\nexport { ModelRawLineChanged };\n/**\n * An event describing that line(s) have been deleted in a model.\n * @internal\n */\nvar ModelRawLinesDeleted = /** @class */ (function () {\n function ModelRawLinesDeleted(fromLineNumber, toLineNumber) {\n this.changeType = 3 /* LinesDeleted */;\n this.fromLineNumber = fromLineNumber;\n this.toLineNumber = toLineNumber;\n }\n return ModelRawLinesDeleted;\n}());\nexport { ModelRawLinesDeleted };\n/**\n * An event describing that line(s) have been inserted in a model.\n * @internal\n */\nvar ModelRawLinesInserted = /** @class */ (function () {\n function ModelRawLinesInserted(fromLineNumber, toLineNumber, detail) {\n this.changeType = 4 /* LinesInserted */;\n this.fromLineNumber = fromLineNumber;\n this.toLineNumber = toLineNumber;\n this.detail = detail;\n }\n return ModelRawLinesInserted;\n}());\nexport { ModelRawLinesInserted };\n/**\n * An event describing that a model has had its EOL changed.\n * @internal\n */\nvar ModelRawEOLChanged = /** @class */ (function () {\n function ModelRawEOLChanged() {\n this.changeType = 5 /* EOLChanged */;\n }\n return ModelRawEOLChanged;\n}());\nexport { ModelRawEOLChanged };\n/**\n * An event describing a change in the text of a model.\n * @internal\n */\nvar ModelRawContentChangedEvent = /** @class */ (function () {\n function ModelRawContentChangedEvent(changes, versionId, isUndoing, isRedoing) {\n this.changes = changes;\n this.versionId = versionId;\n this.isUndoing = isUndoing;\n this.isRedoing = isRedoing;\n }\n ModelRawContentChangedEvent.prototype.containsEvent = function (type) {\n for (var i = 0, len = this.changes.length; i < len; i++) {\n var change = this.changes[i];\n if (change.changeType === type) {\n return true;\n }\n }\n return false;\n };\n ModelRawContentChangedEvent.merge = function (a, b) {\n var changes = [].concat(a.changes).concat(b.changes);\n var versionId = b.versionId;\n var isUndoing = (a.isUndoing || b.isUndoing);\n var isRedoing = (a.isRedoing || b.isRedoing);\n return new ModelRawContentChangedEvent(changes, versionId, isUndoing, isRedoing);\n };\n return ModelRawContentChangedEvent;\n}());\nexport { ModelRawContentChangedEvent };\n/**\n * @internal\n */\nvar InternalModelContentChangeEvent = /** @class */ (function () {\n function InternalModelContentChangeEvent(rawContentChangedEvent, contentChangedEvent) {\n this.rawContentChangedEvent = rawContentChangedEvent;\n this.contentChangedEvent = contentChangedEvent;\n }\n InternalModelContentChangeEvent.prototype.merge = function (other) {\n var rawContentChangedEvent = ModelRawContentChangedEvent.merge(this.rawContentChangedEvent, other.rawContentChangedEvent);\n var contentChangedEvent = InternalModelContentChangeEvent._mergeChangeEvents(this.contentChangedEvent, other.contentChangedEvent);\n return new InternalModelContentChangeEvent(rawContentChangedEvent, contentChangedEvent);\n };\n InternalModelContentChangeEvent._mergeChangeEvents = function (a, b) {\n var changes = [].concat(a.changes).concat(b.changes);\n var eol = b.eol;\n var versionId = b.versionId;\n var isUndoing = (a.isUndoing || b.isUndoing);\n var isRedoing = (a.isRedoing || b.isRedoing);\n var isFlush = (a.isFlush || b.isFlush);\n return {\n changes: changes,\n eol: eol,\n versionId: versionId,\n isUndoing: isUndoing,\n isRedoing: isRedoing,\n isFlush: isFlush\n };\n };\n return InternalModelContentChangeEvent;\n}());\nexport { InternalModelContentChangeEvent };\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport * as arrays from '../../../base/common/arrays.js';\nimport { onUnexpectedError } from '../../../base/common/errors.js';\nimport { LineTokens } from '../core/lineTokens.js';\nimport { Position } from '../core/position.js';\nimport { TokenMetadata } from '../modes.js';\nimport { nullTokenize2 } from '../modes/nullMode.js';\nfunction getDefaultMetadata(topLevelLanguageId) {\n return ((topLevelLanguageId << 0 /* LANGUAGEID_OFFSET */)\n | (0 /* Other */ << 8 /* TOKEN_TYPE_OFFSET */)\n | (0 /* None */ << 11 /* FONT_STYLE_OFFSET */)\n | (1 /* DefaultForeground */ << 14 /* FOREGROUND_OFFSET */)\n | (2 /* DefaultBackground */ << 23 /* BACKGROUND_OFFSET */)) >>> 0;\n}\nvar EMPTY_LINE_TOKENS = (new Uint32Array(0)).buffer;\nvar ModelLineTokens = /** @class */ (function () {\n function ModelLineTokens(state) {\n this._state = state;\n this._lineTokens = null;\n this._invalid = true;\n }\n ModelLineTokens.prototype.deleteBeginning = function (toChIndex) {\n if (this._lineTokens === null || this._lineTokens === EMPTY_LINE_TOKENS) {\n return;\n }\n this.delete(0, toChIndex);\n };\n ModelLineTokens.prototype.deleteEnding = function (fromChIndex) {\n if (this._lineTokens === null || this._lineTokens === EMPTY_LINE_TOKENS) {\n return;\n }\n var tokens = new Uint32Array(this._lineTokens);\n var lineTextLength = tokens[tokens.length - 2];\n this.delete(fromChIndex, lineTextLength);\n };\n ModelLineTokens.prototype.delete = function (fromChIndex, toChIndex) {\n if (this._lineTokens === null || this._lineTokens === EMPTY_LINE_TOKENS || fromChIndex === toChIndex) {\n return;\n }\n var tokens = new Uint32Array(this._lineTokens);\n var tokensCount = (tokens.length >>> 1);\n // special case: deleting everything\n if (fromChIndex === 0 && tokens[tokens.length - 2] === toChIndex) {\n this._lineTokens = EMPTY_LINE_TOKENS;\n return;\n }\n var fromTokenIndex = LineTokens.findIndexInTokensArray(tokens, fromChIndex);\n var fromTokenStartOffset = (fromTokenIndex > 0 ? tokens[(fromTokenIndex - 1) << 1] : 0);\n var fromTokenEndOffset = tokens[fromTokenIndex << 1];\n if (toChIndex < fromTokenEndOffset) {\n // the delete range is inside a single token\n var delta_1 = (toChIndex - fromChIndex);\n for (var i = fromTokenIndex; i < tokensCount; i++) {\n tokens[i << 1] -= delta_1;\n }\n return;\n }\n var dest;\n var lastEnd;\n if (fromTokenStartOffset !== fromChIndex) {\n tokens[fromTokenIndex << 1] = fromChIndex;\n dest = ((fromTokenIndex + 1) << 1);\n lastEnd = fromChIndex;\n }\n else {\n dest = (fromTokenIndex << 1);\n lastEnd = fromTokenStartOffset;\n }\n var delta = (toChIndex - fromChIndex);\n for (var tokenIndex = fromTokenIndex + 1; tokenIndex < tokensCount; tokenIndex++) {\n var tokenEndOffset = tokens[tokenIndex << 1] - delta;\n if (tokenEndOffset > lastEnd) {\n tokens[dest++] = tokenEndOffset;\n tokens[dest++] = tokens[(tokenIndex << 1) + 1];\n lastEnd = tokenEndOffset;\n }\n }\n if (dest === tokens.length) {\n // nothing to trim\n return;\n }\n var tmp = new Uint32Array(dest);\n tmp.set(tokens.subarray(0, dest), 0);\n this._lineTokens = tmp.buffer;\n };\n ModelLineTokens.prototype.append = function (_otherTokens) {\n if (_otherTokens === EMPTY_LINE_TOKENS) {\n return;\n }\n if (this._lineTokens === EMPTY_LINE_TOKENS) {\n this._lineTokens = _otherTokens;\n return;\n }\n if (this._lineTokens === null) {\n return;\n }\n if (_otherTokens === null) {\n // cannot determine combined line length...\n this._lineTokens = null;\n return;\n }\n var myTokens = new Uint32Array(this._lineTokens);\n var otherTokens = new Uint32Array(_otherTokens);\n var otherTokensCount = (otherTokens.length >>> 1);\n var result = new Uint32Array(myTokens.length + otherTokens.length);\n result.set(myTokens, 0);\n var dest = myTokens.length;\n var delta = myTokens[myTokens.length - 2];\n for (var i = 0; i < otherTokensCount; i++) {\n result[dest++] = otherTokens[(i << 1)] + delta;\n result[dest++] = otherTokens[(i << 1) + 1];\n }\n this._lineTokens = result.buffer;\n };\n ModelLineTokens.prototype.insert = function (chIndex, textLength) {\n if (!this._lineTokens) {\n // nothing to do\n return;\n }\n var tokens = new Uint32Array(this._lineTokens);\n var tokensCount = (tokens.length >>> 1);\n var fromTokenIndex = LineTokens.findIndexInTokensArray(tokens, chIndex);\n if (fromTokenIndex > 0) {\n var fromTokenStartOffset = tokens[(fromTokenIndex - 1) << 1];\n if (fromTokenStartOffset === chIndex) {\n fromTokenIndex--;\n }\n }\n for (var tokenIndex = fromTokenIndex; tokenIndex < tokensCount; tokenIndex++) {\n tokens[tokenIndex << 1] += textLength;\n }\n };\n return ModelLineTokens;\n}());\nvar ModelLinesTokens = /** @class */ (function () {\n function ModelLinesTokens(languageIdentifier, tokenizationSupport) {\n this.languageIdentifier = languageIdentifier;\n this.tokenizationSupport = tokenizationSupport;\n this._tokens = [];\n if (this.tokenizationSupport) {\n var initialState = null;\n try {\n initialState = this.tokenizationSupport.getInitialState();\n }\n catch (e) {\n onUnexpectedError(e);\n this.tokenizationSupport = null;\n }\n if (initialState) {\n this._tokens[0] = new ModelLineTokens(initialState);\n }\n }\n this._invalidLineStartIndex = 0;\n this._lastState = null;\n }\n Object.defineProperty(ModelLinesTokens.prototype, \"inValidLineStartIndex\", {\n get: function () {\n return this._invalidLineStartIndex;\n },\n enumerable: true,\n configurable: true\n });\n ModelLinesTokens.prototype.getTokens = function (topLevelLanguageId, lineIndex, lineText) {\n var rawLineTokens = null;\n if (lineIndex < this._tokens.length && this._tokens[lineIndex]) {\n rawLineTokens = this._tokens[lineIndex]._lineTokens;\n }\n if (rawLineTokens !== null && rawLineTokens !== EMPTY_LINE_TOKENS) {\n return new LineTokens(new Uint32Array(rawLineTokens), lineText);\n }\n var lineTokens = new Uint32Array(2);\n lineTokens[0] = lineText.length;\n lineTokens[1] = getDefaultMetadata(topLevelLanguageId);\n return new LineTokens(lineTokens, lineText);\n };\n ModelLinesTokens.prototype.isCheapToTokenize = function (lineNumber) {\n var firstInvalidLineNumber = this._invalidLineStartIndex + 1;\n return (firstInvalidLineNumber >= lineNumber);\n };\n ModelLinesTokens.prototype.hasLinesToTokenize = function (buffer) {\n return (this._invalidLineStartIndex < buffer.getLineCount());\n };\n ModelLinesTokens.prototype.invalidateLine = function (lineIndex) {\n this._setIsInvalid(lineIndex, true);\n if (lineIndex < this._invalidLineStartIndex) {\n this._setIsInvalid(this._invalidLineStartIndex, true);\n this._invalidLineStartIndex = lineIndex;\n }\n };\n ModelLinesTokens.prototype._setIsInvalid = function (lineIndex, invalid) {\n if (lineIndex < this._tokens.length && this._tokens[lineIndex]) {\n this._tokens[lineIndex]._invalid = invalid;\n }\n };\n ModelLinesTokens.prototype._isInvalid = function (lineIndex) {\n if (lineIndex < this._tokens.length && this._tokens[lineIndex]) {\n return this._tokens[lineIndex]._invalid;\n }\n return true;\n };\n ModelLinesTokens.prototype._getState = function (lineIndex) {\n if (lineIndex < this._tokens.length && this._tokens[lineIndex]) {\n return this._tokens[lineIndex]._state;\n }\n return null;\n };\n ModelLinesTokens.prototype._setTokens = function (topLevelLanguageId, lineIndex, lineTextLength, tokens) {\n var target;\n if (lineIndex < this._tokens.length && this._tokens[lineIndex]) {\n target = this._tokens[lineIndex];\n }\n else {\n target = new ModelLineTokens(null);\n this._tokens[lineIndex] = target;\n }\n if (lineTextLength === 0) {\n var hasDifferentLanguageId = false;\n if (tokens && tokens.length > 1) {\n hasDifferentLanguageId = (TokenMetadata.getLanguageId(tokens[1]) !== topLevelLanguageId);\n }\n if (!hasDifferentLanguageId) {\n target._lineTokens = EMPTY_LINE_TOKENS;\n return;\n }\n }\n if (!tokens || tokens.length === 0) {\n tokens = new Uint32Array(2);\n tokens[0] = 0;\n tokens[1] = getDefaultMetadata(topLevelLanguageId);\n }\n LineTokens.convertToEndOffset(tokens, lineTextLength);\n target._lineTokens = tokens.buffer;\n };\n ModelLinesTokens.prototype._setState = function (lineIndex, state) {\n if (lineIndex < this._tokens.length && this._tokens[lineIndex]) {\n this._tokens[lineIndex]._state = state;\n }\n else {\n var tmp = new ModelLineTokens(state);\n this._tokens[lineIndex] = tmp;\n }\n };\n //#region Editing\n ModelLinesTokens.prototype.applyEdits = function (range, eolCount, firstLineLength) {\n var deletingLinesCnt = range.endLineNumber - range.startLineNumber;\n var insertingLinesCnt = eolCount;\n var editingLinesCnt = Math.min(deletingLinesCnt, insertingLinesCnt);\n for (var j = editingLinesCnt; j >= 0; j--) {\n this.invalidateLine(range.startLineNumber + j - 1);\n }\n this._acceptDeleteRange(range);\n this._acceptInsertText(new Position(range.startLineNumber, range.startColumn), eolCount, firstLineLength);\n };\n ModelLinesTokens.prototype._acceptDeleteRange = function (range) {\n var firstLineIndex = range.startLineNumber - 1;\n if (firstLineIndex >= this._tokens.length) {\n return;\n }\n if (range.startLineNumber === range.endLineNumber) {\n if (range.startColumn === range.endColumn) {\n // Nothing to delete\n return;\n }\n this._tokens[firstLineIndex].delete(range.startColumn - 1, range.endColumn - 1);\n return;\n }\n var firstLine = this._tokens[firstLineIndex];\n firstLine.deleteEnding(range.startColumn - 1);\n var lastLineIndex = range.endLineNumber - 1;\n var lastLineTokens = null;\n if (lastLineIndex < this._tokens.length) {\n var lastLine = this._tokens[lastLineIndex];\n lastLine.deleteBeginning(range.endColumn - 1);\n lastLineTokens = lastLine._lineTokens;\n }\n // Take remaining text on last line and append it to remaining text on first line\n firstLine.append(lastLineTokens);\n // Delete middle lines\n this._tokens.splice(range.startLineNumber, range.endLineNumber - range.startLineNumber);\n };\n ModelLinesTokens.prototype._acceptInsertText = function (position, eolCount, firstLineLength) {\n if (eolCount === 0 && firstLineLength === 0) {\n // Nothing to insert\n return;\n }\n var lineIndex = position.lineNumber - 1;\n if (lineIndex >= this._tokens.length) {\n return;\n }\n if (eolCount === 0) {\n // Inserting text on one line\n this._tokens[lineIndex].insert(position.column - 1, firstLineLength);\n return;\n }\n var line = this._tokens[lineIndex];\n line.deleteEnding(position.column - 1);\n line.insert(position.column - 1, firstLineLength);\n var insert = new Array(eolCount);\n for (var i = eolCount - 1; i >= 0; i--) {\n insert[i] = new ModelLineTokens(null);\n }\n this._tokens = arrays.arrayInsert(this._tokens, position.lineNumber, insert);\n };\n //#endregion\n //#region Tokenization\n ModelLinesTokens.prototype._tokenizeOneLine = function (buffer, eventBuilder) {\n if (!this.hasLinesToTokenize(buffer)) {\n return buffer.getLineCount() + 1;\n }\n var lineNumber = this._invalidLineStartIndex + 1;\n this._updateTokensUntilLine(buffer, eventBuilder, lineNumber);\n return lineNumber;\n };\n ModelLinesTokens.prototype._tokenizeText = function (buffer, text, state) {\n var r = null;\n if (this.tokenizationSupport) {\n try {\n r = this.tokenizationSupport.tokenize2(text, state, 0);\n }\n catch (e) {\n onUnexpectedError(e);\n }\n }\n if (!r) {\n r = nullTokenize2(this.languageIdentifier.id, text, state, 0);\n }\n return r;\n };\n ModelLinesTokens.prototype._updateTokensUntilLine = function (buffer, eventBuilder, lineNumber) {\n if (!this.tokenizationSupport) {\n this._invalidLineStartIndex = buffer.getLineCount();\n return;\n }\n var linesLength = buffer.getLineCount();\n var endLineIndex = lineNumber - 1;\n // Validate all states up to and including endLineIndex\n for (var lineIndex = this._invalidLineStartIndex; lineIndex <= endLineIndex; lineIndex++) {\n var endStateIndex = lineIndex + 1;\n var text = buffer.getLineContent(lineIndex + 1);\n var lineStartState = this._getState(lineIndex);\n var r = null;\n try {\n // Tokenize only the first X characters\n var freshState = lineStartState.clone();\n r = this.tokenizationSupport.tokenize2(text, freshState, 0);\n }\n catch (e) {\n onUnexpectedError(e);\n }\n if (!r) {\n r = nullTokenize2(this.languageIdentifier.id, text, lineStartState, 0);\n }\n this._setTokens(this.languageIdentifier.id, lineIndex, text.length, r.tokens);\n eventBuilder.registerChangedTokens(lineIndex + 1);\n this._setIsInvalid(lineIndex, false);\n if (endStateIndex < linesLength) {\n var previousEndState = this._getState(endStateIndex);\n if (previousEndState !== null && r.endState.equals(previousEndState)) {\n // The end state of this line remains the same\n var nextInvalidLineIndex = lineIndex + 1;\n while (nextInvalidLineIndex < linesLength) {\n if (this._isInvalid(nextInvalidLineIndex)) {\n break;\n }\n if (nextInvalidLineIndex + 1 < linesLength) {\n if (this._getState(nextInvalidLineIndex + 1) === null) {\n break;\n }\n }\n else {\n if (this._lastState === null) {\n break;\n }\n }\n nextInvalidLineIndex++;\n }\n this._invalidLineStartIndex = Math.max(this._invalidLineStartIndex, nextInvalidLineIndex);\n lineIndex = nextInvalidLineIndex - 1; // -1 because the outer loop increments it\n }\n else {\n this._setState(endStateIndex, r.endState);\n }\n }\n else {\n this._lastState = r.endState;\n }\n }\n this._invalidLineStartIndex = Math.max(this._invalidLineStartIndex, endLineIndex + 1);\n };\n return ModelLinesTokens;\n}());\nexport { ModelLinesTokens };\nvar ModelTokensChangedEventBuilder = /** @class */ (function () {\n function ModelTokensChangedEventBuilder() {\n this._ranges = [];\n }\n ModelTokensChangedEventBuilder.prototype.registerChangedTokens = function (lineNumber) {\n var ranges = this._ranges;\n var rangesLength = ranges.length;\n var previousRange = rangesLength > 0 ? ranges[rangesLength - 1] : null;\n if (previousRange && previousRange.toLineNumber === lineNumber - 1) {\n // extend previous range\n previousRange.toLineNumber++;\n }\n else {\n // insert new range\n ranges[rangesLength] = {\n fromLineNumber: lineNumber,\n toLineNumber: lineNumber\n };\n }\n };\n ModelTokensChangedEventBuilder.prototype.build = function () {\n if (this._ranges.length === 0) {\n return null;\n }\n return {\n tokenizationSupportChanged: false,\n ranges: this._ranges\n };\n };\n return ModelTokensChangedEventBuilder;\n}());\nexport { ModelTokensChangedEventBuilder };\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { onUnexpectedError } from '../../../base/common/errors.js';\nimport { Emitter } from '../../../base/common/event.js';\nimport { Disposable } from '../../../base/common/lifecycle.js';\nimport { StopWatch } from '../../../base/common/stopwatch.js';\nimport * as strings from '../../../base/common/strings.js';\nimport { URI } from '../../../base/common/uri.js';\nimport { EDITOR_MODEL_DEFAULTS } from '../config/editorOptions.js';\nimport { Position } from '../core/position.js';\nimport { Range } from '../core/range.js';\nimport { Selection } from '../core/selection.js';\nimport * as model from '../model.js';\nimport { EditStack } from './editStack.js';\nimport { guessIndentation } from './indentationGuesser.js';\nimport { IntervalNode, IntervalTree, getNodeIsInOverviewRuler, recomputeMaxEnd } from './intervalTree.js';\nimport { PieceTreeTextBufferBuilder } from './pieceTreeTextBuffer/pieceTreeTextBufferBuilder.js';\nimport { InternalModelContentChangeEvent, ModelRawContentChangedEvent, ModelRawEOLChanged, ModelRawFlush, ModelRawLineChanged, ModelRawLinesDeleted, ModelRawLinesInserted } from './textModelEvents.js';\nimport { SearchParams, TextModelSearch } from './textModelSearch.js';\nimport { ModelLinesTokens, ModelTokensChangedEventBuilder } from './textModelTokens.js';\nimport { getWordAtText } from './wordHelper.js';\nimport { TokenizationRegistry } from '../modes.js';\nimport { LanguageConfigurationRegistry } from '../modes/languageConfigurationRegistry.js';\nimport { NULL_LANGUAGE_IDENTIFIER } from '../modes/nullMode.js';\nimport { ignoreBracketsInToken } from '../modes/supports.js';\nimport { BracketsUtils } from '../modes/supports/richEditBrackets.js';\nimport { withUndefinedAsNull } from '../../../base/common/types.js';\nvar CHEAP_TOKENIZATION_LENGTH_LIMIT = 2048;\nfunction createTextBufferBuilder() {\n return new PieceTreeTextBufferBuilder();\n}\nexport function createTextBufferFactory(text) {\n var builder = createTextBufferBuilder();\n builder.acceptChunk(text);\n return builder.finish();\n}\nexport function createTextBuffer(value, defaultEOL) {\n var factory = (typeof value === 'string' ? createTextBufferFactory(value) : value);\n return factory.create(defaultEOL);\n}\nvar MODEL_ID = 0;\n/**\n * Produces 'a'-'z', followed by 'A'-'Z'... followed by 'a'-'z', etc.\n */\nfunction singleLetter(result) {\n var LETTERS_CNT = (90 /* Z */ - 65 /* A */ + 1);\n result = result % (2 * LETTERS_CNT);\n if (result < LETTERS_CNT) {\n return String.fromCharCode(97 /* a */ + result);\n }\n return String.fromCharCode(65 /* A */ + result - LETTERS_CNT);\n}\nvar LIMIT_FIND_COUNT = 999;\nexport var LONG_LINE_BOUNDARY = 10000;\nvar invalidFunc = function () { throw new Error(\"Invalid change accessor\"); };\nvar TextModel = /** @class */ (function (_super) {\n __extends(TextModel, _super);\n //#endregion\n function TextModel(source, creationOptions, languageIdentifier, associatedResource) {\n if (associatedResource === void 0) { associatedResource = null; }\n var _this = _super.call(this) || this;\n //#region Events\n _this._onWillDispose = _this._register(new Emitter());\n _this.onWillDispose = _this._onWillDispose.event;\n _this._onDidChangeDecorations = _this._register(new DidChangeDecorationsEmitter());\n _this.onDidChangeDecorations = _this._onDidChangeDecorations.event;\n _this._onDidChangeLanguage = _this._register(new Emitter());\n _this.onDidChangeLanguage = _this._onDidChangeLanguage.event;\n _this._onDidChangeLanguageConfiguration = _this._register(new Emitter());\n _this.onDidChangeLanguageConfiguration = _this._onDidChangeLanguageConfiguration.event;\n _this._onDidChangeTokens = _this._register(new Emitter());\n _this.onDidChangeTokens = _this._onDidChangeTokens.event;\n _this._onDidChangeOptions = _this._register(new Emitter());\n _this.onDidChangeOptions = _this._onDidChangeOptions.event;\n _this._eventEmitter = _this._register(new DidChangeContentEmitter());\n // Generate a new unique model id\n MODEL_ID++;\n _this.id = '$model' + MODEL_ID;\n _this.isForSimpleWidget = creationOptions.isForSimpleWidget;\n if (typeof associatedResource === 'undefined' || associatedResource === null) {\n _this._associatedResource = URI.parse('inmemory://model/' + MODEL_ID);\n }\n else {\n _this._associatedResource = associatedResource;\n }\n _this._attachedEditorCount = 0;\n _this._buffer = createTextBuffer(source, creationOptions.defaultEOL);\n _this._options = TextModel.resolveOptions(_this._buffer, creationOptions);\n var bufferLineCount = _this._buffer.getLineCount();\n var bufferTextLength = _this._buffer.getValueLengthInRange(new Range(1, 1, bufferLineCount, _this._buffer.getLineLength(bufferLineCount) + 1), 0 /* TextDefined */);\n // !!! Make a decision in the ctor and permanently respect this decision !!!\n // If a model is too large at construction time, it will never get tokenized,\n // under no circumstances.\n if (creationOptions.largeFileOptimizations) {\n _this._isTooLargeForTokenization = ((bufferTextLength > TextModel.LARGE_FILE_SIZE_THRESHOLD)\n || (bufferLineCount > TextModel.LARGE_FILE_LINE_COUNT_THRESHOLD));\n }\n else {\n _this._isTooLargeForTokenization = false;\n }\n _this._isTooLargeForSyncing = (bufferTextLength > TextModel.MODEL_SYNC_LIMIT);\n _this._setVersionId(1);\n _this._isDisposed = false;\n _this._isDisposing = false;\n _this._languageIdentifier = languageIdentifier || NULL_LANGUAGE_IDENTIFIER;\n _this._tokenizationListener = TokenizationRegistry.onDidChange(function (e) {\n if (e.changedLanguages.indexOf(_this._languageIdentifier.language) === -1) {\n return;\n }\n _this._resetTokenizationState();\n _this.emitModelTokensChangedEvent({\n tokenizationSupportChanged: true,\n ranges: [{\n fromLineNumber: 1,\n toLineNumber: _this.getLineCount()\n }]\n });\n if (_this._shouldAutoTokenize()) {\n _this._warmUpTokens();\n }\n });\n _this._revalidateTokensTimeout = -1;\n _this._languageRegistryListener = LanguageConfigurationRegistry.onDidChange(function (e) {\n if (e.languageIdentifier.id === _this._languageIdentifier.id) {\n _this._onDidChangeLanguageConfiguration.fire({});\n }\n });\n _this._resetTokenizationState();\n _this._instanceId = singleLetter(MODEL_ID);\n _this._lastDecorationId = 0;\n _this._decorations = Object.create(null);\n _this._decorationsTree = new DecorationsTrees();\n _this._commandManager = new EditStack(_this);\n _this._isUndoing = false;\n _this._isRedoing = false;\n _this._trimAutoWhitespaceLines = null;\n return _this;\n }\n TextModel.createFromString = function (text, options, languageIdentifier, uri) {\n if (options === void 0) { options = TextModel.DEFAULT_CREATION_OPTIONS; }\n if (languageIdentifier === void 0) { languageIdentifier = null; }\n if (uri === void 0) { uri = null; }\n return new TextModel(text, options, languageIdentifier, uri);\n };\n TextModel.resolveOptions = function (textBuffer, options) {\n if (options.detectIndentation) {\n var guessedIndentation = guessIndentation(textBuffer, options.tabSize, options.insertSpaces);\n return new model.TextModelResolvedOptions({\n tabSize: guessedIndentation.tabSize,\n indentSize: guessedIndentation.tabSize,\n insertSpaces: guessedIndentation.insertSpaces,\n trimAutoWhitespace: options.trimAutoWhitespace,\n defaultEOL: options.defaultEOL\n });\n }\n return new model.TextModelResolvedOptions({\n tabSize: options.tabSize,\n indentSize: options.indentSize,\n insertSpaces: options.insertSpaces,\n trimAutoWhitespace: options.trimAutoWhitespace,\n defaultEOL: options.defaultEOL\n });\n };\n TextModel.prototype.onDidChangeRawContentFast = function (listener) {\n return this._eventEmitter.fastEvent(function (e) { return listener(e.rawContentChangedEvent); });\n };\n TextModel.prototype.onDidChangeRawContent = function (listener) {\n return this._eventEmitter.slowEvent(function (e) { return listener(e.rawContentChangedEvent); });\n };\n TextModel.prototype.onDidChangeContent = function (listener) {\n return this._eventEmitter.slowEvent(function (e) { return listener(e.contentChangedEvent); });\n };\n TextModel.prototype.dispose = function () {\n this._isDisposing = true;\n this._onWillDispose.fire();\n this._tokenizationListener.dispose();\n this._languageRegistryListener.dispose();\n this._clearTimers();\n this._isDisposed = true;\n // Null out members, such that any use of a disposed model will throw exceptions sooner rather than later\n _super.prototype.dispose.call(this);\n this._isDisposing = false;\n };\n TextModel.prototype._assertNotDisposed = function () {\n if (this._isDisposed) {\n throw new Error('Model is disposed!');\n }\n };\n TextModel.prototype._emitContentChangedEvent = function (rawChange, change) {\n if (this._isDisposing) {\n // Do not confuse listeners by emitting any event after disposing\n return;\n }\n this._eventEmitter.fire(new InternalModelContentChangeEvent(rawChange, change));\n };\n TextModel.prototype.setValue = function (value) {\n this._assertNotDisposed();\n if (value === null) {\n // There's nothing to do\n return;\n }\n var textBuffer = createTextBuffer(value, this._options.defaultEOL);\n this.setValueFromTextBuffer(textBuffer);\n };\n TextModel.prototype._createContentChanged2 = function (range, rangeOffset, rangeLength, text, isUndoing, isRedoing, isFlush) {\n return {\n changes: [{\n range: range,\n rangeOffset: rangeOffset,\n rangeLength: rangeLength,\n text: text,\n }],\n eol: this._buffer.getEOL(),\n versionId: this.getVersionId(),\n isUndoing: isUndoing,\n isRedoing: isRedoing,\n isFlush: isFlush\n };\n };\n TextModel.prototype.setValueFromTextBuffer = function (textBuffer) {\n this._assertNotDisposed();\n if (textBuffer === null) {\n // There's nothing to do\n return;\n }\n var oldFullModelRange = this.getFullModelRange();\n var oldModelValueLength = this.getValueLengthInRange(oldFullModelRange);\n var endLineNumber = this.getLineCount();\n var endColumn = this.getLineMaxColumn(endLineNumber);\n this._buffer = textBuffer;\n this._increaseVersionId();\n // Cancel tokenization, clear all tokens and begin tokenizing\n this._resetTokenizationState();\n // Destroy all my decorations\n this._decorations = Object.create(null);\n this._decorationsTree = new DecorationsTrees();\n // Destroy my edit history and settings\n this._commandManager = new EditStack(this);\n this._trimAutoWhitespaceLines = null;\n this._emitContentChangedEvent(new ModelRawContentChangedEvent([\n new ModelRawFlush()\n ], this._versionId, false, false), this._createContentChanged2(new Range(1, 1, endLineNumber, endColumn), 0, oldModelValueLength, this.getValue(), false, false, true));\n };\n TextModel.prototype.setEOL = function (eol) {\n this._assertNotDisposed();\n var newEOL = (eol === 1 /* CRLF */ ? '\\r\\n' : '\\n');\n if (this._buffer.getEOL() === newEOL) {\n // Nothing to do\n return;\n }\n var oldFullModelRange = this.getFullModelRange();\n var oldModelValueLength = this.getValueLengthInRange(oldFullModelRange);\n var endLineNumber = this.getLineCount();\n var endColumn = this.getLineMaxColumn(endLineNumber);\n this._onBeforeEOLChange();\n this._buffer.setEOL(newEOL);\n this._increaseVersionId();\n this._onAfterEOLChange();\n this._emitContentChangedEvent(new ModelRawContentChangedEvent([\n new ModelRawEOLChanged()\n ], this._versionId, false, false), this._createContentChanged2(new Range(1, 1, endLineNumber, endColumn), 0, oldModelValueLength, this.getValue(), false, false, false));\n };\n TextModel.prototype._onBeforeEOLChange = function () {\n // Ensure all decorations get their `range` set.\n var versionId = this.getVersionId();\n var allDecorations = this._decorationsTree.search(0, false, false, versionId);\n this._ensureNodesHaveRanges(allDecorations);\n };\n TextModel.prototype._onAfterEOLChange = function () {\n // Transform back `range` to offsets\n var versionId = this.getVersionId();\n var allDecorations = this._decorationsTree.collectNodesPostOrder();\n for (var i = 0, len = allDecorations.length; i < len; i++) {\n var node = allDecorations[i];\n var delta = node.cachedAbsoluteStart - node.start;\n var startOffset = this._buffer.getOffsetAt(node.range.startLineNumber, node.range.startColumn);\n var endOffset = this._buffer.getOffsetAt(node.range.endLineNumber, node.range.endColumn);\n node.cachedAbsoluteStart = startOffset;\n node.cachedAbsoluteEnd = endOffset;\n node.cachedVersionId = versionId;\n node.start = startOffset - delta;\n node.end = endOffset - delta;\n recomputeMaxEnd(node);\n }\n };\n TextModel.prototype._resetTokenizationState = function () {\n this._clearTimers();\n var tokenizationSupport = (this._isTooLargeForTokenization\n ? null\n : TokenizationRegistry.get(this._languageIdentifier.language));\n this._tokens = new ModelLinesTokens(this._languageIdentifier, tokenizationSupport);\n this._beginBackgroundTokenization();\n };\n TextModel.prototype._clearTimers = function () {\n if (this._revalidateTokensTimeout !== -1) {\n clearTimeout(this._revalidateTokensTimeout);\n this._revalidateTokensTimeout = -1;\n }\n };\n TextModel.prototype.onBeforeAttached = function () {\n this._attachedEditorCount++;\n // Warm up tokens for the editor\n this._warmUpTokens();\n };\n TextModel.prototype.onBeforeDetached = function () {\n this._attachedEditorCount--;\n };\n TextModel.prototype._shouldAutoTokenize = function () {\n return this.isAttachedToEditor();\n };\n TextModel.prototype.isAttachedToEditor = function () {\n return this._attachedEditorCount > 0;\n };\n TextModel.prototype.getAttachedEditorCount = function () {\n return this._attachedEditorCount;\n };\n TextModel.prototype.isTooLargeForSyncing = function () {\n return this._isTooLargeForSyncing;\n };\n TextModel.prototype.isTooLargeForTokenization = function () {\n return this._isTooLargeForTokenization;\n };\n TextModel.prototype.isDisposed = function () {\n return this._isDisposed;\n };\n TextModel.prototype.isDominatedByLongLines = function () {\n this._assertNotDisposed();\n if (this.isTooLargeForTokenization()) {\n // Cannot word wrap huge files anyways, so it doesn't really matter\n return false;\n }\n var smallLineCharCount = 0;\n var longLineCharCount = 0;\n var lineCount = this._buffer.getLineCount();\n for (var lineNumber = 1; lineNumber <= lineCount; lineNumber++) {\n var lineLength = this._buffer.getLineLength(lineNumber);\n if (lineLength >= LONG_LINE_BOUNDARY) {\n longLineCharCount += lineLength;\n }\n else {\n smallLineCharCount += lineLength;\n }\n }\n return (longLineCharCount > smallLineCharCount);\n };\n Object.defineProperty(TextModel.prototype, \"uri\", {\n get: function () {\n return this._associatedResource;\n },\n enumerable: true,\n configurable: true\n });\n //#region Options\n TextModel.prototype.getOptions = function () {\n this._assertNotDisposed();\n return this._options;\n };\n TextModel.prototype.getFormattingOptions = function () {\n return {\n tabSize: this._options.indentSize,\n insertSpaces: this._options.insertSpaces\n };\n };\n TextModel.prototype.updateOptions = function (_newOpts) {\n this._assertNotDisposed();\n var tabSize = (typeof _newOpts.tabSize !== 'undefined') ? _newOpts.tabSize : this._options.tabSize;\n var indentSize = (typeof _newOpts.indentSize !== 'undefined') ? _newOpts.indentSize : this._options.indentSize;\n var insertSpaces = (typeof _newOpts.insertSpaces !== 'undefined') ? _newOpts.insertSpaces : this._options.insertSpaces;\n var trimAutoWhitespace = (typeof _newOpts.trimAutoWhitespace !== 'undefined') ? _newOpts.trimAutoWhitespace : this._options.trimAutoWhitespace;\n var newOpts = new model.TextModelResolvedOptions({\n tabSize: tabSize,\n indentSize: indentSize,\n insertSpaces: insertSpaces,\n defaultEOL: this._options.defaultEOL,\n trimAutoWhitespace: trimAutoWhitespace\n });\n if (this._options.equals(newOpts)) {\n return;\n }\n var e = this._options.createChangeEvent(newOpts);\n this._options = newOpts;\n this._onDidChangeOptions.fire(e);\n };\n TextModel.prototype.detectIndentation = function (defaultInsertSpaces, defaultTabSize) {\n this._assertNotDisposed();\n var guessedIndentation = guessIndentation(this._buffer, defaultTabSize, defaultInsertSpaces);\n this.updateOptions({\n insertSpaces: guessedIndentation.insertSpaces,\n tabSize: guessedIndentation.tabSize,\n indentSize: guessedIndentation.tabSize,\n });\n };\n TextModel._normalizeIndentationFromWhitespace = function (str, indentSize, insertSpaces) {\n var spacesCnt = 0;\n for (var i = 0; i < str.length; i++) {\n if (str.charAt(i) === '\\t') {\n spacesCnt += indentSize;\n }\n else {\n spacesCnt++;\n }\n }\n var result = '';\n if (!insertSpaces) {\n var tabsCnt = Math.floor(spacesCnt / indentSize);\n spacesCnt = spacesCnt % indentSize;\n for (var i = 0; i < tabsCnt; i++) {\n result += '\\t';\n }\n }\n for (var i = 0; i < spacesCnt; i++) {\n result += ' ';\n }\n return result;\n };\n TextModel.normalizeIndentation = function (str, indentSize, insertSpaces) {\n var firstNonWhitespaceIndex = strings.firstNonWhitespaceIndex(str);\n if (firstNonWhitespaceIndex === -1) {\n firstNonWhitespaceIndex = str.length;\n }\n return TextModel._normalizeIndentationFromWhitespace(str.substring(0, firstNonWhitespaceIndex), indentSize, insertSpaces) + str.substring(firstNonWhitespaceIndex);\n };\n TextModel.prototype.normalizeIndentation = function (str) {\n this._assertNotDisposed();\n return TextModel.normalizeIndentation(str, this._options.indentSize, this._options.insertSpaces);\n };\n //#endregion\n //#region Reading\n TextModel.prototype.getVersionId = function () {\n this._assertNotDisposed();\n return this._versionId;\n };\n TextModel.prototype.mightContainRTL = function () {\n return this._buffer.mightContainRTL();\n };\n TextModel.prototype.mightContainNonBasicASCII = function () {\n return this._buffer.mightContainNonBasicASCII();\n };\n TextModel.prototype.getAlternativeVersionId = function () {\n this._assertNotDisposed();\n return this._alternativeVersionId;\n };\n TextModel.prototype.getOffsetAt = function (rawPosition) {\n this._assertNotDisposed();\n var position = this._validatePosition(rawPosition.lineNumber, rawPosition.column, false);\n return this._buffer.getOffsetAt(position.lineNumber, position.column);\n };\n TextModel.prototype.getPositionAt = function (rawOffset) {\n this._assertNotDisposed();\n var offset = (Math.min(this._buffer.getLength(), Math.max(0, rawOffset)));\n return this._buffer.getPositionAt(offset);\n };\n TextModel.prototype._increaseVersionId = function () {\n this._setVersionId(this._versionId + 1);\n };\n TextModel.prototype._setVersionId = function (newVersionId) {\n this._versionId = newVersionId;\n this._alternativeVersionId = this._versionId;\n };\n TextModel.prototype._overwriteAlternativeVersionId = function (newAlternativeVersionId) {\n this._alternativeVersionId = newAlternativeVersionId;\n };\n TextModel.prototype.getValue = function (eol, preserveBOM) {\n if (preserveBOM === void 0) { preserveBOM = false; }\n this._assertNotDisposed();\n var fullModelRange = this.getFullModelRange();\n var fullModelValue = this.getValueInRange(fullModelRange, eol);\n if (preserveBOM) {\n return this._buffer.getBOM() + fullModelValue;\n }\n return fullModelValue;\n };\n TextModel.prototype.getValueLength = function (eol, preserveBOM) {\n if (preserveBOM === void 0) { preserveBOM = false; }\n this._assertNotDisposed();\n var fullModelRange = this.getFullModelRange();\n var fullModelValue = this.getValueLengthInRange(fullModelRange, eol);\n if (preserveBOM) {\n return this._buffer.getBOM().length + fullModelValue;\n }\n return fullModelValue;\n };\n TextModel.prototype.getValueInRange = function (rawRange, eol) {\n if (eol === void 0) { eol = 0 /* TextDefined */; }\n this._assertNotDisposed();\n return this._buffer.getValueInRange(this.validateRange(rawRange), eol);\n };\n TextModel.prototype.getValueLengthInRange = function (rawRange, eol) {\n if (eol === void 0) { eol = 0 /* TextDefined */; }\n this._assertNotDisposed();\n return this._buffer.getValueLengthInRange(this.validateRange(rawRange), eol);\n };\n TextModel.prototype.getLineCount = function () {\n this._assertNotDisposed();\n return this._buffer.getLineCount();\n };\n TextModel.prototype.getLineContent = function (lineNumber) {\n this._assertNotDisposed();\n if (lineNumber < 1 || lineNumber > this.getLineCount()) {\n throw new Error('Illegal value for lineNumber');\n }\n return this._buffer.getLineContent(lineNumber);\n };\n TextModel.prototype.getLineLength = function (lineNumber) {\n this._assertNotDisposed();\n if (lineNumber < 1 || lineNumber > this.getLineCount()) {\n throw new Error('Illegal value for lineNumber');\n }\n return this._buffer.getLineLength(lineNumber);\n };\n TextModel.prototype.getLinesContent = function () {\n this._assertNotDisposed();\n return this._buffer.getLinesContent();\n };\n TextModel.prototype.getEOL = function () {\n this._assertNotDisposed();\n return this._buffer.getEOL();\n };\n TextModel.prototype.getLineMinColumn = function (lineNumber) {\n this._assertNotDisposed();\n return 1;\n };\n TextModel.prototype.getLineMaxColumn = function (lineNumber) {\n this._assertNotDisposed();\n if (lineNumber < 1 || lineNumber > this.getLineCount()) {\n throw new Error('Illegal value for lineNumber');\n }\n return this._buffer.getLineLength(lineNumber) + 1;\n };\n TextModel.prototype.getLineFirstNonWhitespaceColumn = function (lineNumber) {\n this._assertNotDisposed();\n if (lineNumber < 1 || lineNumber > this.getLineCount()) {\n throw new Error('Illegal value for lineNumber');\n }\n return this._buffer.getLineFirstNonWhitespaceColumn(lineNumber);\n };\n TextModel.prototype.getLineLastNonWhitespaceColumn = function (lineNumber) {\n this._assertNotDisposed();\n if (lineNumber < 1 || lineNumber > this.getLineCount()) {\n throw new Error('Illegal value for lineNumber');\n }\n return this._buffer.getLineLastNonWhitespaceColumn(lineNumber);\n };\n /**\n * Validates `range` is within buffer bounds, but allows it to sit in between surrogate pairs, etc.\n * Will try to not allocate if possible.\n */\n TextModel.prototype._validateRangeRelaxedNoAllocations = function (range) {\n var linesCount = this._buffer.getLineCount();\n var initialStartLineNumber = range.startLineNumber;\n var initialStartColumn = range.startColumn;\n var startLineNumber;\n var startColumn;\n if (initialStartLineNumber < 1) {\n startLineNumber = 1;\n startColumn = 1;\n }\n else if (initialStartLineNumber > linesCount) {\n startLineNumber = linesCount;\n startColumn = this.getLineMaxColumn(startLineNumber);\n }\n else {\n startLineNumber = initialStartLineNumber | 0;\n if (initialStartColumn <= 1) {\n startColumn = 1;\n }\n else {\n var maxColumn = this.getLineMaxColumn(startLineNumber);\n if (initialStartColumn >= maxColumn) {\n startColumn = maxColumn;\n }\n else {\n startColumn = initialStartColumn | 0;\n }\n }\n }\n var initialEndLineNumber = range.endLineNumber;\n var initialEndColumn = range.endColumn;\n var endLineNumber;\n var endColumn;\n if (initialEndLineNumber < 1) {\n endLineNumber = 1;\n endColumn = 1;\n }\n else if (initialEndLineNumber > linesCount) {\n endLineNumber = linesCount;\n endColumn = this.getLineMaxColumn(endLineNumber);\n }\n else {\n endLineNumber = initialEndLineNumber | 0;\n if (initialEndColumn <= 1) {\n endColumn = 1;\n }\n else {\n var maxColumn = this.getLineMaxColumn(endLineNumber);\n if (initialEndColumn >= maxColumn) {\n endColumn = maxColumn;\n }\n else {\n endColumn = initialEndColumn | 0;\n }\n }\n }\n if (initialStartLineNumber === startLineNumber\n && initialStartColumn === startColumn\n && initialEndLineNumber === endLineNumber\n && initialEndColumn === endColumn\n && range instanceof Range\n && !(range instanceof Selection)) {\n return range;\n }\n return new Range(startLineNumber, startColumn, endLineNumber, endColumn);\n };\n /**\n * @param strict Do NOT allow a position inside a high-low surrogate pair\n */\n TextModel.prototype._isValidPosition = function (lineNumber, column, strict) {\n if (typeof lineNumber !== 'number' || typeof column !== 'number') {\n return false;\n }\n if (isNaN(lineNumber) || isNaN(column)) {\n return false;\n }\n if (lineNumber < 1 || column < 1) {\n return false;\n }\n if ((lineNumber | 0) !== lineNumber || (column | 0) !== column) {\n return false;\n }\n var lineCount = this._buffer.getLineCount();\n if (lineNumber > lineCount) {\n return false;\n }\n var maxColumn = this.getLineMaxColumn(lineNumber);\n if (column > maxColumn) {\n return false;\n }\n if (strict) {\n if (column > 1) {\n var charCodeBefore = this._buffer.getLineCharCode(lineNumber, column - 2);\n if (strings.isHighSurrogate(charCodeBefore)) {\n return false;\n }\n }\n }\n return true;\n };\n /**\n * @param strict Do NOT allow a position inside a high-low surrogate pair\n */\n TextModel.prototype._validatePosition = function (_lineNumber, _column, strict) {\n var lineNumber = Math.floor((typeof _lineNumber === 'number' && !isNaN(_lineNumber)) ? _lineNumber : 1);\n var column = Math.floor((typeof _column === 'number' && !isNaN(_column)) ? _column : 1);\n var lineCount = this._buffer.getLineCount();\n if (lineNumber < 1) {\n return new Position(1, 1);\n }\n if (lineNumber > lineCount) {\n return new Position(lineCount, this.getLineMaxColumn(lineCount));\n }\n if (column <= 1) {\n return new Position(lineNumber, 1);\n }\n var maxColumn = this.getLineMaxColumn(lineNumber);\n if (column >= maxColumn) {\n return new Position(lineNumber, maxColumn);\n }\n if (strict) {\n // If the position would end up in the middle of a high-low surrogate pair,\n // we move it to before the pair\n // !!At this point, column > 1\n var charCodeBefore = this._buffer.getLineCharCode(lineNumber, column - 2);\n if (strings.isHighSurrogate(charCodeBefore)) {\n return new Position(lineNumber, column - 1);\n }\n }\n return new Position(lineNumber, column);\n };\n TextModel.prototype.validatePosition = function (position) {\n this._assertNotDisposed();\n // Avoid object allocation and cover most likely case\n if (position instanceof Position) {\n if (this._isValidPosition(position.lineNumber, position.column, true)) {\n return position;\n }\n }\n return this._validatePosition(position.lineNumber, position.column, true);\n };\n /**\n * @param strict Do NOT allow a range to have its boundaries inside a high-low surrogate pair\n */\n TextModel.prototype._isValidRange = function (range, strict) {\n var startLineNumber = range.startLineNumber;\n var startColumn = range.startColumn;\n var endLineNumber = range.endLineNumber;\n var endColumn = range.endColumn;\n if (!this._isValidPosition(startLineNumber, startColumn, false)) {\n return false;\n }\n if (!this._isValidPosition(endLineNumber, endColumn, false)) {\n return false;\n }\n if (strict) {\n var charCodeBeforeStart = (startColumn > 1 ? this._buffer.getLineCharCode(startLineNumber, startColumn - 2) : 0);\n var charCodeBeforeEnd = (endColumn > 1 && endColumn <= this._buffer.getLineLength(endLineNumber) ? this._buffer.getLineCharCode(endLineNumber, endColumn - 2) : 0);\n var startInsideSurrogatePair = strings.isHighSurrogate(charCodeBeforeStart);\n var endInsideSurrogatePair = strings.isHighSurrogate(charCodeBeforeEnd);\n if (!startInsideSurrogatePair && !endInsideSurrogatePair) {\n return true;\n }\n return false;\n }\n return true;\n };\n TextModel.prototype.validateRange = function (_range) {\n this._assertNotDisposed();\n // Avoid object allocation and cover most likely case\n if ((_range instanceof Range) && !(_range instanceof Selection)) {\n if (this._isValidRange(_range, true)) {\n return _range;\n }\n }\n var start = this._validatePosition(_range.startLineNumber, _range.startColumn, false);\n var end = this._validatePosition(_range.endLineNumber, _range.endColumn, false);\n var startLineNumber = start.lineNumber;\n var startColumn = start.column;\n var endLineNumber = end.lineNumber;\n var endColumn = end.column;\n var charCodeBeforeStart = (startColumn > 1 ? this._buffer.getLineCharCode(startLineNumber, startColumn - 2) : 0);\n var charCodeBeforeEnd = (endColumn > 1 && endColumn <= this._buffer.getLineLength(endLineNumber) ? this._buffer.getLineCharCode(endLineNumber, endColumn - 2) : 0);\n var startInsideSurrogatePair = strings.isHighSurrogate(charCodeBeforeStart);\n var endInsideSurrogatePair = strings.isHighSurrogate(charCodeBeforeEnd);\n if (!startInsideSurrogatePair && !endInsideSurrogatePair) {\n return new Range(startLineNumber, startColumn, endLineNumber, endColumn);\n }\n if (startLineNumber === endLineNumber && startColumn === endColumn) {\n // do not expand a collapsed range, simply move it to a valid location\n return new Range(startLineNumber, startColumn - 1, endLineNumber, endColumn - 1);\n }\n if (startInsideSurrogatePair && endInsideSurrogatePair) {\n // expand range at both ends\n return new Range(startLineNumber, startColumn - 1, endLineNumber, endColumn + 1);\n }\n if (startInsideSurrogatePair) {\n // only expand range at the start\n return new Range(startLineNumber, startColumn - 1, endLineNumber, endColumn);\n }\n // only expand range at the end\n return new Range(startLineNumber, startColumn, endLineNumber, endColumn + 1);\n };\n TextModel.prototype.modifyPosition = function (rawPosition, offset) {\n this._assertNotDisposed();\n var candidate = this.getOffsetAt(rawPosition) + offset;\n return this.getPositionAt(Math.min(this._buffer.getLength(), Math.max(0, candidate)));\n };\n TextModel.prototype.getFullModelRange = function () {\n this._assertNotDisposed();\n var lineCount = this.getLineCount();\n return new Range(1, 1, lineCount, this.getLineMaxColumn(lineCount));\n };\n TextModel.prototype.findMatchesLineByLine = function (searchRange, searchData, captureMatches, limitResultCount) {\n return this._buffer.findMatchesLineByLine(searchRange, searchData, captureMatches, limitResultCount);\n };\n TextModel.prototype.findMatches = function (searchString, rawSearchScope, isRegex, matchCase, wordSeparators, captureMatches, limitResultCount) {\n if (limitResultCount === void 0) { limitResultCount = LIMIT_FIND_COUNT; }\n this._assertNotDisposed();\n var searchRange;\n if (Range.isIRange(rawSearchScope)) {\n searchRange = this.validateRange(rawSearchScope);\n }\n else {\n searchRange = this.getFullModelRange();\n }\n if (!isRegex && searchString.indexOf('\\n') < 0) {\n // not regex, not multi line\n var searchParams = new SearchParams(searchString, isRegex, matchCase, wordSeparators);\n var searchData = searchParams.parseSearchRequest();\n if (!searchData) {\n return [];\n }\n return this.findMatchesLineByLine(searchRange, searchData, captureMatches, limitResultCount);\n }\n return TextModelSearch.findMatches(this, new SearchParams(searchString, isRegex, matchCase, wordSeparators), searchRange, captureMatches, limitResultCount);\n };\n TextModel.prototype.findNextMatch = function (searchString, rawSearchStart, isRegex, matchCase, wordSeparators, captureMatches) {\n this._assertNotDisposed();\n var searchStart = this.validatePosition(rawSearchStart);\n if (!isRegex && searchString.indexOf('\\n') < 0) {\n var searchParams = new SearchParams(searchString, isRegex, matchCase, wordSeparators);\n var searchData = searchParams.parseSearchRequest();\n if (!searchData) {\n return null;\n }\n var lineCount = this.getLineCount();\n var searchRange = new Range(searchStart.lineNumber, searchStart.column, lineCount, this.getLineMaxColumn(lineCount));\n var ret = this.findMatchesLineByLine(searchRange, searchData, captureMatches, 1);\n TextModelSearch.findNextMatch(this, new SearchParams(searchString, isRegex, matchCase, wordSeparators), searchStart, captureMatches);\n if (ret.length > 0) {\n return ret[0];\n }\n searchRange = new Range(1, 1, searchStart.lineNumber, this.getLineMaxColumn(searchStart.lineNumber));\n ret = this.findMatchesLineByLine(searchRange, searchData, captureMatches, 1);\n if (ret.length > 0) {\n return ret[0];\n }\n return null;\n }\n return TextModelSearch.findNextMatch(this, new SearchParams(searchString, isRegex, matchCase, wordSeparators), searchStart, captureMatches);\n };\n TextModel.prototype.findPreviousMatch = function (searchString, rawSearchStart, isRegex, matchCase, wordSeparators, captureMatches) {\n this._assertNotDisposed();\n var searchStart = this.validatePosition(rawSearchStart);\n return TextModelSearch.findPreviousMatch(this, new SearchParams(searchString, isRegex, matchCase, wordSeparators), searchStart, captureMatches);\n };\n //#endregion\n //#region Editing\n TextModel.prototype.pushStackElement = function () {\n this._commandManager.pushStackElement();\n };\n TextModel.prototype.pushEOL = function (eol) {\n var currentEOL = (this.getEOL() === '\\n' ? 0 /* LF */ : 1 /* CRLF */);\n if (currentEOL === eol) {\n return;\n }\n try {\n this._onDidChangeDecorations.beginDeferredEmit();\n this._eventEmitter.beginDeferredEmit();\n this._commandManager.pushEOL(eol);\n }\n finally {\n this._eventEmitter.endDeferredEmit();\n this._onDidChangeDecorations.endDeferredEmit();\n }\n };\n TextModel.prototype.pushEditOperations = function (beforeCursorState, editOperations, cursorStateComputer) {\n try {\n this._onDidChangeDecorations.beginDeferredEmit();\n this._eventEmitter.beginDeferredEmit();\n return this._pushEditOperations(beforeCursorState, editOperations, cursorStateComputer);\n }\n finally {\n this._eventEmitter.endDeferredEmit();\n this._onDidChangeDecorations.endDeferredEmit();\n }\n };\n TextModel.prototype._pushEditOperations = function (beforeCursorState, editOperations, cursorStateComputer) {\n var _this = this;\n if (this._options.trimAutoWhitespace && this._trimAutoWhitespaceLines) {\n // Go through each saved line number and insert a trim whitespace edit\n // if it is safe to do so (no conflicts with other edits).\n var incomingEdits = editOperations.map(function (op) {\n return {\n range: _this.validateRange(op.range),\n text: op.text\n };\n });\n // Sometimes, auto-formatters change ranges automatically which can cause undesired auto whitespace trimming near the cursor\n // We'll use the following heuristic: if the edits occur near the cursor, then it's ok to trim auto whitespace\n var editsAreNearCursors = true;\n for (var i = 0, len = beforeCursorState.length; i < len; i++) {\n var sel = beforeCursorState[i];\n var foundEditNearSel = false;\n for (var j = 0, lenJ = incomingEdits.length; j < lenJ; j++) {\n var editRange = incomingEdits[j].range;\n var selIsAbove = editRange.startLineNumber > sel.endLineNumber;\n var selIsBelow = sel.startLineNumber > editRange.endLineNumber;\n if (!selIsAbove && !selIsBelow) {\n foundEditNearSel = true;\n break;\n }\n }\n if (!foundEditNearSel) {\n editsAreNearCursors = false;\n break;\n }\n }\n if (editsAreNearCursors) {\n for (var i = 0, len = this._trimAutoWhitespaceLines.length; i < len; i++) {\n var trimLineNumber = this._trimAutoWhitespaceLines[i];\n var maxLineColumn = this.getLineMaxColumn(trimLineNumber);\n var allowTrimLine = true;\n for (var j = 0, lenJ = incomingEdits.length; j < lenJ; j++) {\n var editRange = incomingEdits[j].range;\n var editText = incomingEdits[j].text;\n if (trimLineNumber < editRange.startLineNumber || trimLineNumber > editRange.endLineNumber) {\n // `trimLine` is completely outside this edit\n continue;\n }\n // At this point:\n // editRange.startLineNumber <= trimLine <= editRange.endLineNumber\n if (trimLineNumber === editRange.startLineNumber && editRange.startColumn === maxLineColumn\n && editRange.isEmpty() && editText && editText.length > 0 && editText.charAt(0) === '\\n') {\n // This edit inserts a new line (and maybe other text) after `trimLine`\n continue;\n }\n if (trimLineNumber === editRange.startLineNumber && editRange.startColumn === 1\n && editRange.isEmpty() && editText && editText.length > 0 && editText.charAt(editText.length - 1) === '\\n') {\n // This edit inserts a new line (and maybe other text) before `trimLine`\n continue;\n }\n // Looks like we can't trim this line as it would interfere with an incoming edit\n allowTrimLine = false;\n break;\n }\n if (allowTrimLine) {\n editOperations.push({\n range: new Range(trimLineNumber, 1, trimLineNumber, maxLineColumn),\n text: null\n });\n }\n }\n }\n this._trimAutoWhitespaceLines = null;\n }\n return this._commandManager.pushEditOperation(beforeCursorState, editOperations, cursorStateComputer);\n };\n TextModel.prototype.applyEdits = function (rawOperations) {\n try {\n this._onDidChangeDecorations.beginDeferredEmit();\n this._eventEmitter.beginDeferredEmit();\n return this._applyEdits(rawOperations);\n }\n finally {\n this._eventEmitter.endDeferredEmit();\n this._onDidChangeDecorations.endDeferredEmit();\n }\n };\n TextModel._eolCount = function (text) {\n var eolCount = 0;\n var firstLineLength = 0;\n for (var i = 0, len = text.length; i < len; i++) {\n var chr = text.charCodeAt(i);\n if (chr === 13 /* CarriageReturn */) {\n if (eolCount === 0) {\n firstLineLength = i;\n }\n eolCount++;\n if (i + 1 < len && text.charCodeAt(i + 1) === 10 /* LineFeed */) {\n // \\r\\n... case\n i++; // skip \\n\n }\n else {\n // \\r... case\n }\n }\n else if (chr === 10 /* LineFeed */) {\n if (eolCount === 0) {\n firstLineLength = i;\n }\n eolCount++;\n }\n }\n if (eolCount === 0) {\n firstLineLength = text.length;\n }\n return [eolCount, firstLineLength];\n };\n TextModel.prototype._applyEdits = function (rawOperations) {\n for (var i = 0, len = rawOperations.length; i < len; i++) {\n rawOperations[i].range = this.validateRange(rawOperations[i].range);\n }\n var oldLineCount = this._buffer.getLineCount();\n var result = this._buffer.applyEdits(rawOperations, this._options.trimAutoWhitespace);\n var newLineCount = this._buffer.getLineCount();\n var contentChanges = result.changes;\n this._trimAutoWhitespaceLines = result.trimAutoWhitespaceLineNumbers;\n if (contentChanges.length !== 0) {\n var rawContentChanges = [];\n var lineCount = oldLineCount;\n for (var i = 0, len = contentChanges.length; i < len; i++) {\n var change = contentChanges[i];\n var _a = TextModel._eolCount(change.text), eolCount = _a[0], firstLineLength = _a[1];\n try {\n this._tokens.applyEdits(change.range, eolCount, firstLineLength);\n }\n catch (err) {\n // emergency recovery => reset tokens\n this._tokens = new ModelLinesTokens(this._tokens.languageIdentifier, this._tokens.tokenizationSupport);\n }\n this._onDidChangeDecorations.fire();\n this._decorationsTree.acceptReplace(change.rangeOffset, change.rangeLength, change.text.length, change.forceMoveMarkers);\n var startLineNumber = change.range.startLineNumber;\n var endLineNumber = change.range.endLineNumber;\n var deletingLinesCnt = endLineNumber - startLineNumber;\n var insertingLinesCnt = eolCount;\n var editingLinesCnt = Math.min(deletingLinesCnt, insertingLinesCnt);\n var changeLineCountDelta = (insertingLinesCnt - deletingLinesCnt);\n for (var j = editingLinesCnt; j >= 0; j--) {\n var editLineNumber = startLineNumber + j;\n var currentEditLineNumber = newLineCount - lineCount - changeLineCountDelta + editLineNumber;\n rawContentChanges.push(new ModelRawLineChanged(editLineNumber, this.getLineContent(currentEditLineNumber)));\n }\n if (editingLinesCnt < deletingLinesCnt) {\n // Must delete some lines\n var spliceStartLineNumber = startLineNumber + editingLinesCnt;\n rawContentChanges.push(new ModelRawLinesDeleted(spliceStartLineNumber + 1, endLineNumber));\n }\n if (editingLinesCnt < insertingLinesCnt) {\n // Must insert some lines\n var spliceLineNumber = startLineNumber + editingLinesCnt;\n var cnt = insertingLinesCnt - editingLinesCnt;\n var fromLineNumber = newLineCount - lineCount - cnt + spliceLineNumber + 1;\n var newLines = [];\n for (var i_1 = 0; i_1 < cnt; i_1++) {\n var lineNumber = fromLineNumber + i_1;\n newLines[lineNumber - fromLineNumber] = this.getLineContent(lineNumber);\n }\n rawContentChanges.push(new ModelRawLinesInserted(spliceLineNumber + 1, startLineNumber + insertingLinesCnt, newLines));\n }\n lineCount += changeLineCountDelta;\n }\n this._increaseVersionId();\n this._emitContentChangedEvent(new ModelRawContentChangedEvent(rawContentChanges, this.getVersionId(), this._isUndoing, this._isRedoing), {\n changes: contentChanges,\n eol: this._buffer.getEOL(),\n versionId: this.getVersionId(),\n isUndoing: this._isUndoing,\n isRedoing: this._isRedoing,\n isFlush: false\n });\n }\n if (this._tokens.hasLinesToTokenize(this._buffer)) {\n this._beginBackgroundTokenization();\n }\n return result.reverseEdits;\n };\n TextModel.prototype._undo = function () {\n this._isUndoing = true;\n var r = this._commandManager.undo();\n this._isUndoing = false;\n if (!r) {\n return null;\n }\n this._overwriteAlternativeVersionId(r.recordedVersionId);\n return r.selections;\n };\n TextModel.prototype.undo = function () {\n try {\n this._onDidChangeDecorations.beginDeferredEmit();\n this._eventEmitter.beginDeferredEmit();\n return this._undo();\n }\n finally {\n this._eventEmitter.endDeferredEmit();\n this._onDidChangeDecorations.endDeferredEmit();\n }\n };\n TextModel.prototype.canUndo = function () {\n return this._commandManager.canUndo();\n };\n TextModel.prototype._redo = function () {\n this._isRedoing = true;\n var r = this._commandManager.redo();\n this._isRedoing = false;\n if (!r) {\n return null;\n }\n this._overwriteAlternativeVersionId(r.recordedVersionId);\n return r.selections;\n };\n TextModel.prototype.redo = function () {\n try {\n this._onDidChangeDecorations.beginDeferredEmit();\n this._eventEmitter.beginDeferredEmit();\n return this._redo();\n }\n finally {\n this._eventEmitter.endDeferredEmit();\n this._onDidChangeDecorations.endDeferredEmit();\n }\n };\n TextModel.prototype.canRedo = function () {\n return this._commandManager.canRedo();\n };\n //#endregion\n //#region Decorations\n TextModel.prototype.changeDecorations = function (callback, ownerId) {\n if (ownerId === void 0) { ownerId = 0; }\n this._assertNotDisposed();\n try {\n this._onDidChangeDecorations.beginDeferredEmit();\n return this._changeDecorations(ownerId, callback);\n }\n finally {\n this._onDidChangeDecorations.endDeferredEmit();\n }\n };\n TextModel.prototype._changeDecorations = function (ownerId, callback) {\n var _this = this;\n var changeAccessor = {\n addDecoration: function (range, options) {\n _this._onDidChangeDecorations.fire();\n return _this._deltaDecorationsImpl(ownerId, [], [{ range: range, options: options }])[0];\n },\n changeDecoration: function (id, newRange) {\n _this._onDidChangeDecorations.fire();\n _this._changeDecorationImpl(id, newRange);\n },\n changeDecorationOptions: function (id, options) {\n _this._onDidChangeDecorations.fire();\n _this._changeDecorationOptionsImpl(id, _normalizeOptions(options));\n },\n removeDecoration: function (id) {\n _this._onDidChangeDecorations.fire();\n _this._deltaDecorationsImpl(ownerId, [id], []);\n },\n deltaDecorations: function (oldDecorations, newDecorations) {\n if (oldDecorations.length === 0 && newDecorations.length === 0) {\n // nothing to do\n return [];\n }\n _this._onDidChangeDecorations.fire();\n return _this._deltaDecorationsImpl(ownerId, oldDecorations, newDecorations);\n }\n };\n var result = null;\n try {\n result = callback(changeAccessor);\n }\n catch (e) {\n onUnexpectedError(e);\n }\n // Invalidate change accessor\n changeAccessor.addDecoration = invalidFunc;\n changeAccessor.changeDecoration = invalidFunc;\n changeAccessor.changeDecorationOptions = invalidFunc;\n changeAccessor.removeDecoration = invalidFunc;\n changeAccessor.deltaDecorations = invalidFunc;\n return result;\n };\n TextModel.prototype.deltaDecorations = function (oldDecorations, newDecorations, ownerId) {\n if (ownerId === void 0) { ownerId = 0; }\n this._assertNotDisposed();\n if (!oldDecorations) {\n oldDecorations = [];\n }\n if (oldDecorations.length === 0 && newDecorations.length === 0) {\n // nothing to do\n return [];\n }\n try {\n this._onDidChangeDecorations.beginDeferredEmit();\n this._onDidChangeDecorations.fire();\n return this._deltaDecorationsImpl(ownerId, oldDecorations, newDecorations);\n }\n finally {\n this._onDidChangeDecorations.endDeferredEmit();\n }\n };\n TextModel.prototype._getTrackedRange = function (id) {\n return this.getDecorationRange(id);\n };\n TextModel.prototype._setTrackedRange = function (id, newRange, newStickiness) {\n var node = (id ? this._decorations[id] : null);\n if (!node) {\n if (!newRange) {\n // node doesn't exist, the request is to delete => nothing to do\n return null;\n }\n // node doesn't exist, the request is to set => add the tracked range\n return this._deltaDecorationsImpl(0, [], [{ range: newRange, options: TRACKED_RANGE_OPTIONS[newStickiness] }])[0];\n }\n if (!newRange) {\n // node exists, the request is to delete => delete node\n this._decorationsTree.delete(node);\n delete this._decorations[node.id];\n return null;\n }\n // node exists, the request is to set => change the tracked range and its options\n var range = this._validateRangeRelaxedNoAllocations(newRange);\n var startOffset = this._buffer.getOffsetAt(range.startLineNumber, range.startColumn);\n var endOffset = this._buffer.getOffsetAt(range.endLineNumber, range.endColumn);\n this._decorationsTree.delete(node);\n node.reset(this.getVersionId(), startOffset, endOffset, range);\n node.setOptions(TRACKED_RANGE_OPTIONS[newStickiness]);\n this._decorationsTree.insert(node);\n return node.id;\n };\n TextModel.prototype.removeAllDecorationsWithOwnerId = function (ownerId) {\n if (this._isDisposed) {\n return;\n }\n var nodes = this._decorationsTree.collectNodesFromOwner(ownerId);\n for (var i = 0, len = nodes.length; i < len; i++) {\n var node = nodes[i];\n this._decorationsTree.delete(node);\n delete this._decorations[node.id];\n }\n };\n TextModel.prototype.getDecorationOptions = function (decorationId) {\n var node = this._decorations[decorationId];\n if (!node) {\n return null;\n }\n return node.options;\n };\n TextModel.prototype.getDecorationRange = function (decorationId) {\n var node = this._decorations[decorationId];\n if (!node) {\n return null;\n }\n var versionId = this.getVersionId();\n if (node.cachedVersionId !== versionId) {\n this._decorationsTree.resolveNode(node, versionId);\n }\n if (node.range === null) {\n node.range = this._getRangeAt(node.cachedAbsoluteStart, node.cachedAbsoluteEnd);\n }\n return node.range;\n };\n TextModel.prototype.getLineDecorations = function (lineNumber, ownerId, filterOutValidation) {\n if (ownerId === void 0) { ownerId = 0; }\n if (filterOutValidation === void 0) { filterOutValidation = false; }\n if (lineNumber < 1 || lineNumber > this.getLineCount()) {\n return [];\n }\n return this.getLinesDecorations(lineNumber, lineNumber, ownerId, filterOutValidation);\n };\n TextModel.prototype.getLinesDecorations = function (_startLineNumber, _endLineNumber, ownerId, filterOutValidation) {\n if (ownerId === void 0) { ownerId = 0; }\n if (filterOutValidation === void 0) { filterOutValidation = false; }\n var lineCount = this.getLineCount();\n var startLineNumber = Math.min(lineCount, Math.max(1, _startLineNumber));\n var endLineNumber = Math.min(lineCount, Math.max(1, _endLineNumber));\n var endColumn = this.getLineMaxColumn(endLineNumber);\n return this._getDecorationsInRange(new Range(startLineNumber, 1, endLineNumber, endColumn), ownerId, filterOutValidation);\n };\n TextModel.prototype.getDecorationsInRange = function (range, ownerId, filterOutValidation) {\n if (ownerId === void 0) { ownerId = 0; }\n if (filterOutValidation === void 0) { filterOutValidation = false; }\n var validatedRange = this.validateRange(range);\n return this._getDecorationsInRange(validatedRange, ownerId, filterOutValidation);\n };\n TextModel.prototype.getOverviewRulerDecorations = function (ownerId, filterOutValidation) {\n if (ownerId === void 0) { ownerId = 0; }\n if (filterOutValidation === void 0) { filterOutValidation = false; }\n var versionId = this.getVersionId();\n var result = this._decorationsTree.search(ownerId, filterOutValidation, true, versionId);\n return this._ensureNodesHaveRanges(result);\n };\n TextModel.prototype.getAllDecorations = function (ownerId, filterOutValidation) {\n if (ownerId === void 0) { ownerId = 0; }\n if (filterOutValidation === void 0) { filterOutValidation = false; }\n var versionId = this.getVersionId();\n var result = this._decorationsTree.search(ownerId, filterOutValidation, false, versionId);\n return this._ensureNodesHaveRanges(result);\n };\n TextModel.prototype._getDecorationsInRange = function (filterRange, filterOwnerId, filterOutValidation) {\n var startOffset = this._buffer.getOffsetAt(filterRange.startLineNumber, filterRange.startColumn);\n var endOffset = this._buffer.getOffsetAt(filterRange.endLineNumber, filterRange.endColumn);\n var versionId = this.getVersionId();\n var result = this._decorationsTree.intervalSearch(startOffset, endOffset, filterOwnerId, filterOutValidation, versionId);\n return this._ensureNodesHaveRanges(result);\n };\n TextModel.prototype._ensureNodesHaveRanges = function (nodes) {\n for (var i = 0, len = nodes.length; i < len; i++) {\n var node = nodes[i];\n if (node.range === null) {\n node.range = this._getRangeAt(node.cachedAbsoluteStart, node.cachedAbsoluteEnd);\n }\n }\n return nodes;\n };\n TextModel.prototype._getRangeAt = function (start, end) {\n return this._buffer.getRangeAt(start, end - start);\n };\n TextModel.prototype._changeDecorationImpl = function (decorationId, _range) {\n var node = this._decorations[decorationId];\n if (!node) {\n return;\n }\n var range = this._validateRangeRelaxedNoAllocations(_range);\n var startOffset = this._buffer.getOffsetAt(range.startLineNumber, range.startColumn);\n var endOffset = this._buffer.getOffsetAt(range.endLineNumber, range.endColumn);\n this._decorationsTree.delete(node);\n node.reset(this.getVersionId(), startOffset, endOffset, range);\n this._decorationsTree.insert(node);\n };\n TextModel.prototype._changeDecorationOptionsImpl = function (decorationId, options) {\n var node = this._decorations[decorationId];\n if (!node) {\n return;\n }\n var nodeWasInOverviewRuler = (node.options.overviewRuler && node.options.overviewRuler.color ? true : false);\n var nodeIsInOverviewRuler = (options.overviewRuler && options.overviewRuler.color ? true : false);\n if (nodeWasInOverviewRuler !== nodeIsInOverviewRuler) {\n // Delete + Insert due to an overview ruler status change\n this._decorationsTree.delete(node);\n node.setOptions(options);\n this._decorationsTree.insert(node);\n }\n else {\n node.setOptions(options);\n }\n };\n TextModel.prototype._deltaDecorationsImpl = function (ownerId, oldDecorationsIds, newDecorations) {\n var versionId = this.getVersionId();\n var oldDecorationsLen = oldDecorationsIds.length;\n var oldDecorationIndex = 0;\n var newDecorationsLen = newDecorations.length;\n var newDecorationIndex = 0;\n var result = new Array(newDecorationsLen);\n while (oldDecorationIndex < oldDecorationsLen || newDecorationIndex < newDecorationsLen) {\n var node = null;\n if (oldDecorationIndex < oldDecorationsLen) {\n // (1) get ourselves an old node\n do {\n node = this._decorations[oldDecorationsIds[oldDecorationIndex++]];\n } while (!node && oldDecorationIndex < oldDecorationsLen);\n // (2) remove the node from the tree (if it exists)\n if (node) {\n this._decorationsTree.delete(node);\n }\n }\n if (newDecorationIndex < newDecorationsLen) {\n // (3) create a new node if necessary\n if (!node) {\n var internalDecorationId = (++this._lastDecorationId);\n var decorationId = this._instanceId + \";\" + internalDecorationId;\n node = new IntervalNode(decorationId, 0, 0);\n this._decorations[decorationId] = node;\n }\n // (4) initialize node\n var newDecoration = newDecorations[newDecorationIndex];\n var range = this._validateRangeRelaxedNoAllocations(newDecoration.range);\n var options = _normalizeOptions(newDecoration.options);\n var startOffset = this._buffer.getOffsetAt(range.startLineNumber, range.startColumn);\n var endOffset = this._buffer.getOffsetAt(range.endLineNumber, range.endColumn);\n node.ownerId = ownerId;\n node.reset(versionId, startOffset, endOffset, range);\n node.setOptions(options);\n this._decorationsTree.insert(node);\n result[newDecorationIndex] = node.id;\n newDecorationIndex++;\n }\n else {\n if (node) {\n delete this._decorations[node.id];\n }\n }\n }\n return result;\n };\n //#endregion\n //#region Tokenization\n TextModel.prototype.tokenizeViewport = function (startLineNumber, endLineNumber) {\n if (!this._tokens.tokenizationSupport) {\n // nothing to do\n return;\n }\n startLineNumber = Math.max(1, startLineNumber);\n endLineNumber = Math.min(this.getLineCount(), endLineNumber);\n if (endLineNumber <= this._tokens.inValidLineStartIndex) {\n // nothing to do\n return;\n }\n if (startLineNumber <= this._tokens.inValidLineStartIndex) {\n // tokenization has reached the viewport start...\n this.forceTokenization(endLineNumber);\n return;\n }\n var nonWhitespaceColumn = this.getLineFirstNonWhitespaceColumn(startLineNumber);\n var fakeLines = [];\n var initialState = null;\n for (var i = startLineNumber - 1; nonWhitespaceColumn > 0 && i >= 1; i--) {\n var newNonWhitespaceIndex = this.getLineFirstNonWhitespaceColumn(i);\n if (newNonWhitespaceIndex === 0) {\n continue;\n }\n if (newNonWhitespaceIndex < nonWhitespaceColumn) {\n initialState = this._tokens._getState(i - 1);\n if (initialState) {\n break;\n }\n fakeLines.push(this.getLineContent(i));\n nonWhitespaceColumn = newNonWhitespaceIndex;\n }\n }\n if (!initialState) {\n initialState = this._tokens.tokenizationSupport.getInitialState();\n }\n var state = initialState.clone();\n for (var i = fakeLines.length - 1; i >= 0; i--) {\n var r = this._tokens._tokenizeText(this._buffer, fakeLines[i], state);\n if (r) {\n state = r.endState.clone();\n }\n else {\n state = initialState.clone();\n }\n }\n var eventBuilder = new ModelTokensChangedEventBuilder();\n for (var i = startLineNumber; i <= endLineNumber; i++) {\n var text = this.getLineContent(i);\n var r = this._tokens._tokenizeText(this._buffer, text, state);\n if (r) {\n this._tokens._setTokens(this._tokens.languageIdentifier.id, i - 1, text.length, r.tokens);\n // We cannot trust these states/tokens to be valid!\n // (see https://github.com/Microsoft/vscode/issues/67607)\n this._tokens._setIsInvalid(i - 1, true);\n this._tokens._setState(i - 1, state);\n state = r.endState.clone();\n eventBuilder.registerChangedTokens(i);\n }\n else {\n state = initialState.clone();\n }\n }\n var e = eventBuilder.build();\n if (e) {\n this._onDidChangeTokens.fire(e);\n }\n };\n TextModel.prototype.flushTokens = function () {\n this._resetTokenizationState();\n this.emitModelTokensChangedEvent({\n tokenizationSupportChanged: false,\n ranges: [{\n fromLineNumber: 1,\n toLineNumber: this.getLineCount()\n }]\n });\n };\n TextModel.prototype.forceTokenization = function (lineNumber) {\n if (lineNumber < 1 || lineNumber > this.getLineCount()) {\n throw new Error('Illegal value for lineNumber');\n }\n var eventBuilder = new ModelTokensChangedEventBuilder();\n this._tokens._updateTokensUntilLine(this._buffer, eventBuilder, lineNumber);\n var e = eventBuilder.build();\n if (e) {\n this._onDidChangeTokens.fire(e);\n }\n };\n TextModel.prototype.isCheapToTokenize = function (lineNumber) {\n if (!this._tokens.isCheapToTokenize(lineNumber)) {\n return false;\n }\n if (lineNumber < this._tokens.inValidLineStartIndex + 1) {\n return true;\n }\n if (this.getLineLength(lineNumber) < CHEAP_TOKENIZATION_LENGTH_LIMIT) {\n return true;\n }\n return false;\n };\n TextModel.prototype.tokenizeIfCheap = function (lineNumber) {\n if (this.isCheapToTokenize(lineNumber)) {\n this.forceTokenization(lineNumber);\n }\n };\n TextModel.prototype.getLineTokens = function (lineNumber) {\n if (lineNumber < 1 || lineNumber > this.getLineCount()) {\n throw new Error('Illegal value for lineNumber');\n }\n return this._getLineTokens(lineNumber);\n };\n TextModel.prototype._getLineTokens = function (lineNumber) {\n var lineText = this._buffer.getLineContent(lineNumber);\n return this._tokens.getTokens(this._languageIdentifier.id, lineNumber - 1, lineText);\n };\n TextModel.prototype.getLanguageIdentifier = function () {\n return this._languageIdentifier;\n };\n TextModel.prototype.getModeId = function () {\n return this._languageIdentifier.language;\n };\n TextModel.prototype.setMode = function (languageIdentifier) {\n if (this._languageIdentifier.id === languageIdentifier.id) {\n // There's nothing to do\n return;\n }\n var e = {\n oldLanguage: this._languageIdentifier.language,\n newLanguage: languageIdentifier.language\n };\n this._languageIdentifier = languageIdentifier;\n // Cancel tokenization, clear all tokens and begin tokenizing\n this._resetTokenizationState();\n this.emitModelTokensChangedEvent({\n tokenizationSupportChanged: true,\n ranges: [{\n fromLineNumber: 1,\n toLineNumber: this.getLineCount()\n }]\n });\n this._onDidChangeLanguage.fire(e);\n this._onDidChangeLanguageConfiguration.fire({});\n };\n TextModel.prototype.getLanguageIdAtPosition = function (_lineNumber, _column) {\n if (!this._tokens.tokenizationSupport) {\n return this._languageIdentifier.id;\n }\n var _a = this.validatePosition({ lineNumber: _lineNumber, column: _column }), lineNumber = _a.lineNumber, column = _a.column;\n var lineTokens = this._getLineTokens(lineNumber);\n return lineTokens.getLanguageId(lineTokens.findTokenIndexAtOffset(column - 1));\n };\n TextModel.prototype._beginBackgroundTokenization = function () {\n var _this = this;\n if (this._shouldAutoTokenize() && this._revalidateTokensTimeout === -1) {\n this._revalidateTokensTimeout = setTimeout(function () {\n _this._revalidateTokensTimeout = -1;\n _this._revalidateTokensNow();\n }, 0);\n }\n };\n TextModel.prototype._warmUpTokens = function () {\n // Warm up first 100 lines (if it takes less than 50ms)\n var maxLineNumber = Math.min(100, this.getLineCount());\n this._revalidateTokensNow(maxLineNumber);\n if (this._tokens.hasLinesToTokenize(this._buffer)) {\n this._beginBackgroundTokenization();\n }\n };\n TextModel.prototype._revalidateTokensNow = function (toLineNumber) {\n if (toLineNumber === void 0) { toLineNumber = this._buffer.getLineCount(); }\n var MAX_ALLOWED_TIME = 20;\n var eventBuilder = new ModelTokensChangedEventBuilder();\n var sw = StopWatch.create(false);\n while (this._tokens.hasLinesToTokenize(this._buffer)) {\n if (sw.elapsed() > MAX_ALLOWED_TIME) {\n // Stop if MAX_ALLOWED_TIME is reached\n break;\n }\n var tokenizedLineNumber = this._tokens._tokenizeOneLine(this._buffer, eventBuilder);\n if (tokenizedLineNumber >= toLineNumber) {\n break;\n }\n }\n if (this._tokens.hasLinesToTokenize(this._buffer)) {\n this._beginBackgroundTokenization();\n }\n var e = eventBuilder.build();\n if (e) {\n this._onDidChangeTokens.fire(e);\n }\n };\n TextModel.prototype.emitModelTokensChangedEvent = function (e) {\n if (!this._isDisposing) {\n this._onDidChangeTokens.fire(e);\n }\n };\n // Having tokens allows implementing additional helper methods\n TextModel.prototype.getWordAtPosition = function (_position) {\n this._assertNotDisposed();\n var position = this.validatePosition(_position);\n var lineContent = this.getLineContent(position.lineNumber);\n var lineTokens = this._getLineTokens(position.lineNumber);\n var tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1);\n // (1). First try checking right biased word\n var _a = TextModel._findLanguageBoundaries(lineTokens, tokenIndex), rbStartOffset = _a[0], rbEndOffset = _a[1];\n var rightBiasedWord = getWordAtText(position.column, LanguageConfigurationRegistry.getWordDefinition(lineTokens.getLanguageId(tokenIndex)), lineContent.substring(rbStartOffset, rbEndOffset), rbStartOffset);\n // Make sure the result touches the original passed in position\n if (rightBiasedWord && rightBiasedWord.startColumn <= _position.column && _position.column <= rightBiasedWord.endColumn) {\n return rightBiasedWord;\n }\n // (2). Else, if we were at a language boundary, check the left biased word\n if (tokenIndex > 0 && rbStartOffset === position.column - 1) {\n // edge case, where `position` sits between two tokens belonging to two different languages\n var _b = TextModel._findLanguageBoundaries(lineTokens, tokenIndex - 1), lbStartOffset = _b[0], lbEndOffset = _b[1];\n var leftBiasedWord = getWordAtText(position.column, LanguageConfigurationRegistry.getWordDefinition(lineTokens.getLanguageId(tokenIndex - 1)), lineContent.substring(lbStartOffset, lbEndOffset), lbStartOffset);\n // Make sure the result touches the original passed in position\n if (leftBiasedWord && leftBiasedWord.startColumn <= _position.column && _position.column <= leftBiasedWord.endColumn) {\n return leftBiasedWord;\n }\n }\n return null;\n };\n TextModel._findLanguageBoundaries = function (lineTokens, tokenIndex) {\n var languageId = lineTokens.getLanguageId(tokenIndex);\n // go left until a different language is hit\n var startOffset = 0;\n for (var i = tokenIndex; i >= 0 && lineTokens.getLanguageId(i) === languageId; i--) {\n startOffset = lineTokens.getStartOffset(i);\n }\n // go right until a different language is hit\n var endOffset = lineTokens.getLineContent().length;\n for (var i = tokenIndex, tokenCount = lineTokens.getCount(); i < tokenCount && lineTokens.getLanguageId(i) === languageId; i++) {\n endOffset = lineTokens.getEndOffset(i);\n }\n return [startOffset, endOffset];\n };\n TextModel.prototype.getWordUntilPosition = function (position) {\n var wordAtPosition = this.getWordAtPosition(position);\n if (!wordAtPosition) {\n return {\n word: '',\n startColumn: position.column,\n endColumn: position.column\n };\n }\n return {\n word: wordAtPosition.word.substr(0, position.column - wordAtPosition.startColumn),\n startColumn: wordAtPosition.startColumn,\n endColumn: position.column\n };\n };\n TextModel.prototype.findMatchingBracketUp = function (_bracket, _position) {\n var bracket = _bracket.toLowerCase();\n var position = this.validatePosition(_position);\n var lineTokens = this._getLineTokens(position.lineNumber);\n var languageId = lineTokens.getLanguageId(lineTokens.findTokenIndexAtOffset(position.column - 1));\n var bracketsSupport = LanguageConfigurationRegistry.getBracketsSupport(languageId);\n if (!bracketsSupport) {\n return null;\n }\n var data = bracketsSupport.textIsBracket[bracket];\n if (!data) {\n return null;\n }\n return this._findMatchingBracketUp(data, position);\n };\n TextModel.prototype.matchBracket = function (position) {\n return this._matchBracket(this.validatePosition(position));\n };\n TextModel.prototype._matchBracket = function (position) {\n var lineNumber = position.lineNumber;\n var lineTokens = this._getLineTokens(lineNumber);\n var lineText = this._buffer.getLineContent(lineNumber);\n var tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1);\n if (tokenIndex < 0) {\n return null;\n }\n var currentModeBrackets = LanguageConfigurationRegistry.getBracketsSupport(lineTokens.getLanguageId(tokenIndex));\n // check that the token is not to be ignored\n if (currentModeBrackets && !ignoreBracketsInToken(lineTokens.getStandardTokenType(tokenIndex))) {\n // limit search to not go before `maxBracketLength`\n var searchStartOffset = Math.max(lineTokens.getStartOffset(tokenIndex), position.column - 1 - currentModeBrackets.maxBracketLength);\n // limit search to not go after `maxBracketLength`\n var searchEndOffset = Math.min(lineTokens.getEndOffset(tokenIndex), position.column - 1 + currentModeBrackets.maxBracketLength);\n // it might be the case that [currentTokenStart -> currentTokenEnd] contains multiple brackets\n // `bestResult` will contain the most right-side result\n var bestResult = null;\n while (true) {\n var foundBracket = BracketsUtils.findNextBracketInToken(currentModeBrackets.forwardRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);\n if (!foundBracket) {\n // there are no more brackets in this text\n break;\n }\n // check that we didn't hit a bracket too far away from position\n if (foundBracket.startColumn <= position.column && position.column <= foundBracket.endColumn) {\n var foundBracketText = lineText.substring(foundBracket.startColumn - 1, foundBracket.endColumn - 1);\n foundBracketText = foundBracketText.toLowerCase();\n var r = this._matchFoundBracket(foundBracket, currentModeBrackets.textIsBracket[foundBracketText], currentModeBrackets.textIsOpenBracket[foundBracketText]);\n // check that we can actually match this bracket\n if (r) {\n bestResult = r;\n }\n }\n searchStartOffset = foundBracket.endColumn - 1;\n }\n if (bestResult) {\n return bestResult;\n }\n }\n // If position is in between two tokens, try also looking in the previous token\n if (tokenIndex > 0 && lineTokens.getStartOffset(tokenIndex) === position.column - 1) {\n var searchEndOffset = lineTokens.getStartOffset(tokenIndex);\n tokenIndex--;\n var prevModeBrackets = LanguageConfigurationRegistry.getBracketsSupport(lineTokens.getLanguageId(tokenIndex));\n // check that previous token is not to be ignored\n if (prevModeBrackets && !ignoreBracketsInToken(lineTokens.getStandardTokenType(tokenIndex))) {\n // limit search in case previous token is very large, there's no need to go beyond `maxBracketLength`\n var searchStartOffset = Math.max(lineTokens.getStartOffset(tokenIndex), position.column - 1 - prevModeBrackets.maxBracketLength);\n var foundBracket = BracketsUtils.findPrevBracketInToken(prevModeBrackets.reversedRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);\n // check that we didn't hit a bracket too far away from position\n if (foundBracket && foundBracket.startColumn <= position.column && position.column <= foundBracket.endColumn) {\n var foundBracketText = lineText.substring(foundBracket.startColumn - 1, foundBracket.endColumn - 1);\n foundBracketText = foundBracketText.toLowerCase();\n var r = this._matchFoundBracket(foundBracket, prevModeBrackets.textIsBracket[foundBracketText], prevModeBrackets.textIsOpenBracket[foundBracketText]);\n // check that we can actually match this bracket\n if (r) {\n return r;\n }\n }\n }\n }\n return null;\n };\n TextModel.prototype._matchFoundBracket = function (foundBracket, data, isOpen) {\n if (!data) {\n return null;\n }\n if (isOpen) {\n var matched = this._findMatchingBracketDown(data, foundBracket.getEndPosition());\n if (matched) {\n return [foundBracket, matched];\n }\n }\n else {\n var matched = this._findMatchingBracketUp(data, foundBracket.getStartPosition());\n if (matched) {\n return [foundBracket, matched];\n }\n }\n return null;\n };\n TextModel.prototype._findMatchingBracketUp = function (bracket, position) {\n // console.log('_findMatchingBracketUp: ', 'bracket: ', JSON.stringify(bracket), 'startPosition: ', String(position));\n var languageId = bracket.languageIdentifier.id;\n var reversedBracketRegex = bracket.reversedRegex;\n var count = -1;\n for (var lineNumber = position.lineNumber; lineNumber >= 1; lineNumber--) {\n var lineTokens = this._getLineTokens(lineNumber);\n var tokenCount = lineTokens.getCount();\n var lineText = this._buffer.getLineContent(lineNumber);\n var tokenIndex = tokenCount - 1;\n var searchStopOffset = -1;\n if (lineNumber === position.lineNumber) {\n tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1);\n searchStopOffset = position.column - 1;\n }\n for (; tokenIndex >= 0; tokenIndex--) {\n var tokenLanguageId = lineTokens.getLanguageId(tokenIndex);\n var tokenType = lineTokens.getStandardTokenType(tokenIndex);\n var tokenStartOffset = lineTokens.getStartOffset(tokenIndex);\n var tokenEndOffset = lineTokens.getEndOffset(tokenIndex);\n if (searchStopOffset === -1) {\n searchStopOffset = tokenEndOffset;\n }\n if (tokenLanguageId === languageId && !ignoreBracketsInToken(tokenType)) {\n while (true) {\n var r = BracketsUtils.findPrevBracketInToken(reversedBracketRegex, lineNumber, lineText, tokenStartOffset, searchStopOffset);\n if (!r) {\n break;\n }\n var hitText = lineText.substring(r.startColumn - 1, r.endColumn - 1);\n hitText = hitText.toLowerCase();\n if (hitText === bracket.open) {\n count++;\n }\n else if (hitText === bracket.close) {\n count--;\n }\n if (count === 0) {\n return r;\n }\n searchStopOffset = r.startColumn - 1;\n }\n }\n searchStopOffset = -1;\n }\n }\n return null;\n };\n TextModel.prototype._findMatchingBracketDown = function (bracket, position) {\n // console.log('_findMatchingBracketDown: ', 'bracket: ', JSON.stringify(bracket), 'startPosition: ', String(position));\n var languageId = bracket.languageIdentifier.id;\n var bracketRegex = bracket.forwardRegex;\n var count = 1;\n for (var lineNumber = position.lineNumber, lineCount = this.getLineCount(); lineNumber <= lineCount; lineNumber++) {\n var lineTokens = this._getLineTokens(lineNumber);\n var tokenCount = lineTokens.getCount();\n var lineText = this._buffer.getLineContent(lineNumber);\n var tokenIndex = 0;\n var searchStartOffset = 0;\n if (lineNumber === position.lineNumber) {\n tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1);\n searchStartOffset = position.column - 1;\n }\n for (; tokenIndex < tokenCount; tokenIndex++) {\n var tokenLanguageId = lineTokens.getLanguageId(tokenIndex);\n var tokenType = lineTokens.getStandardTokenType(tokenIndex);\n var tokenStartOffset = lineTokens.getStartOffset(tokenIndex);\n var tokenEndOffset = lineTokens.getEndOffset(tokenIndex);\n if (searchStartOffset === 0) {\n searchStartOffset = tokenStartOffset;\n }\n if (tokenLanguageId === languageId && !ignoreBracketsInToken(tokenType)) {\n while (true) {\n var r = BracketsUtils.findNextBracketInToken(bracketRegex, lineNumber, lineText, searchStartOffset, tokenEndOffset);\n if (!r) {\n break;\n }\n var hitText = lineText.substring(r.startColumn - 1, r.endColumn - 1);\n hitText = hitText.toLowerCase();\n if (hitText === bracket.open) {\n count++;\n }\n else if (hitText === bracket.close) {\n count--;\n }\n if (count === 0) {\n return r;\n }\n searchStartOffset = r.endColumn - 1;\n }\n }\n searchStartOffset = 0;\n }\n }\n return null;\n };\n TextModel.prototype.findPrevBracket = function (_position) {\n var position = this.validatePosition(_position);\n var languageId = -1;\n var modeBrackets = null;\n for (var lineNumber = position.lineNumber; lineNumber >= 1; lineNumber--) {\n var lineTokens = this._getLineTokens(lineNumber);\n var tokenCount = lineTokens.getCount();\n var lineText = this._buffer.getLineContent(lineNumber);\n var tokenIndex = tokenCount - 1;\n var searchStopOffset = -1;\n if (lineNumber === position.lineNumber) {\n tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1);\n searchStopOffset = position.column - 1;\n }\n for (; tokenIndex >= 0; tokenIndex--) {\n var tokenLanguageId = lineTokens.getLanguageId(tokenIndex);\n var tokenType = lineTokens.getStandardTokenType(tokenIndex);\n var tokenStartOffset = lineTokens.getStartOffset(tokenIndex);\n var tokenEndOffset = lineTokens.getEndOffset(tokenIndex);\n if (searchStopOffset === -1) {\n searchStopOffset = tokenEndOffset;\n }\n if (languageId !== tokenLanguageId) {\n languageId = tokenLanguageId;\n modeBrackets = LanguageConfigurationRegistry.getBracketsSupport(languageId);\n }\n if (modeBrackets && !ignoreBracketsInToken(tokenType)) {\n var r = BracketsUtils.findPrevBracketInToken(modeBrackets.reversedRegex, lineNumber, lineText, tokenStartOffset, searchStopOffset);\n if (r) {\n return this._toFoundBracket(modeBrackets, r);\n }\n }\n searchStopOffset = -1;\n }\n }\n return null;\n };\n TextModel.prototype.findNextBracket = function (_position) {\n var position = this.validatePosition(_position);\n var languageId = -1;\n var modeBrackets = null;\n for (var lineNumber = position.lineNumber, lineCount = this.getLineCount(); lineNumber <= lineCount; lineNumber++) {\n var lineTokens = this._getLineTokens(lineNumber);\n var tokenCount = lineTokens.getCount();\n var lineText = this._buffer.getLineContent(lineNumber);\n var tokenIndex = 0;\n var searchStartOffset = 0;\n if (lineNumber === position.lineNumber) {\n tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1);\n searchStartOffset = position.column - 1;\n }\n for (; tokenIndex < tokenCount; tokenIndex++) {\n var tokenLanguageId = lineTokens.getLanguageId(tokenIndex);\n var tokenType = lineTokens.getStandardTokenType(tokenIndex);\n var tokenStartOffset = lineTokens.getStartOffset(tokenIndex);\n var tokenEndOffset = lineTokens.getEndOffset(tokenIndex);\n if (searchStartOffset === 0) {\n searchStartOffset = tokenStartOffset;\n }\n if (languageId !== tokenLanguageId) {\n languageId = tokenLanguageId;\n modeBrackets = LanguageConfigurationRegistry.getBracketsSupport(languageId);\n }\n if (modeBrackets && !ignoreBracketsInToken(tokenType)) {\n var r = BracketsUtils.findNextBracketInToken(modeBrackets.forwardRegex, lineNumber, lineText, searchStartOffset, tokenEndOffset);\n if (r) {\n return this._toFoundBracket(modeBrackets, r);\n }\n }\n searchStartOffset = 0;\n }\n }\n return null;\n };\n TextModel.prototype._toFoundBracket = function (modeBrackets, r) {\n if (!r) {\n return null;\n }\n var text = this.getValueInRange(r);\n text = text.toLowerCase();\n var data = modeBrackets.textIsBracket[text];\n if (!data) {\n return null;\n }\n return {\n range: r,\n open: data.open,\n close: data.close,\n isOpen: modeBrackets.textIsOpenBracket[text]\n };\n };\n /**\n * Returns:\n * - -1 => the line consists of whitespace\n * - otherwise => the indent level is returned value\n */\n TextModel.computeIndentLevel = function (line, tabSize) {\n var indent = 0;\n var i = 0;\n var len = line.length;\n while (i < len) {\n var chCode = line.charCodeAt(i);\n if (chCode === 32 /* Space */) {\n indent++;\n }\n else if (chCode === 9 /* Tab */) {\n indent = indent - indent % tabSize + tabSize;\n }\n else {\n break;\n }\n i++;\n }\n if (i === len) {\n return -1; // line only consists of whitespace\n }\n return indent;\n };\n TextModel.prototype._computeIndentLevel = function (lineIndex) {\n return TextModel.computeIndentLevel(this._buffer.getLineContent(lineIndex + 1), this._options.tabSize);\n };\n TextModel.prototype.getActiveIndentGuide = function (lineNumber, minLineNumber, maxLineNumber) {\n var _this = this;\n this._assertNotDisposed();\n var lineCount = this.getLineCount();\n if (lineNumber < 1 || lineNumber > lineCount) {\n throw new Error('Illegal value for lineNumber');\n }\n var foldingRules = LanguageConfigurationRegistry.getFoldingRules(this._languageIdentifier.id);\n var offSide = Boolean(foldingRules && foldingRules.offSide);\n var up_aboveContentLineIndex = -2; /* -2 is a marker for not having computed it */\n var up_aboveContentLineIndent = -1;\n var up_belowContentLineIndex = -2; /* -2 is a marker for not having computed it */\n var up_belowContentLineIndent = -1;\n var up_resolveIndents = function (lineNumber) {\n if (up_aboveContentLineIndex !== -1 && (up_aboveContentLineIndex === -2 || up_aboveContentLineIndex > lineNumber - 1)) {\n up_aboveContentLineIndex = -1;\n up_aboveContentLineIndent = -1;\n // must find previous line with content\n for (var lineIndex = lineNumber - 2; lineIndex >= 0; lineIndex--) {\n var indent_1 = _this._computeIndentLevel(lineIndex);\n if (indent_1 >= 0) {\n up_aboveContentLineIndex = lineIndex;\n up_aboveContentLineIndent = indent_1;\n break;\n }\n }\n }\n if (up_belowContentLineIndex === -2) {\n up_belowContentLineIndex = -1;\n up_belowContentLineIndent = -1;\n // must find next line with content\n for (var lineIndex = lineNumber; lineIndex < lineCount; lineIndex++) {\n var indent_2 = _this._computeIndentLevel(lineIndex);\n if (indent_2 >= 0) {\n up_belowContentLineIndex = lineIndex;\n up_belowContentLineIndent = indent_2;\n break;\n }\n }\n }\n };\n var down_aboveContentLineIndex = -2; /* -2 is a marker for not having computed it */\n var down_aboveContentLineIndent = -1;\n var down_belowContentLineIndex = -2; /* -2 is a marker for not having computed it */\n var down_belowContentLineIndent = -1;\n var down_resolveIndents = function (lineNumber) {\n if (down_aboveContentLineIndex === -2) {\n down_aboveContentLineIndex = -1;\n down_aboveContentLineIndent = -1;\n // must find previous line with content\n for (var lineIndex = lineNumber - 2; lineIndex >= 0; lineIndex--) {\n var indent_3 = _this._computeIndentLevel(lineIndex);\n if (indent_3 >= 0) {\n down_aboveContentLineIndex = lineIndex;\n down_aboveContentLineIndent = indent_3;\n break;\n }\n }\n }\n if (down_belowContentLineIndex !== -1 && (down_belowContentLineIndex === -2 || down_belowContentLineIndex < lineNumber - 1)) {\n down_belowContentLineIndex = -1;\n down_belowContentLineIndent = -1;\n // must find next line with content\n for (var lineIndex = lineNumber; lineIndex < lineCount; lineIndex++) {\n var indent_4 = _this._computeIndentLevel(lineIndex);\n if (indent_4 >= 0) {\n down_belowContentLineIndex = lineIndex;\n down_belowContentLineIndent = indent_4;\n break;\n }\n }\n }\n };\n var startLineNumber = 0;\n var goUp = true;\n var endLineNumber = 0;\n var goDown = true;\n var indent = 0;\n for (var distance = 0; goUp || goDown; distance++) {\n var upLineNumber = lineNumber - distance;\n var downLineNumber = lineNumber + distance;\n if (distance !== 0 && (upLineNumber < 1 || upLineNumber < minLineNumber)) {\n goUp = false;\n }\n if (distance !== 0 && (downLineNumber > lineCount || downLineNumber > maxLineNumber)) {\n goDown = false;\n }\n if (distance > 50000) {\n // stop processing\n goUp = false;\n goDown = false;\n }\n if (goUp) {\n // compute indent level going up\n var upLineIndentLevel = void 0;\n var currentIndent = this._computeIndentLevel(upLineNumber - 1);\n if (currentIndent >= 0) {\n // This line has content (besides whitespace)\n // Use the line's indent\n up_belowContentLineIndex = upLineNumber - 1;\n up_belowContentLineIndent = currentIndent;\n upLineIndentLevel = Math.ceil(currentIndent / this._options.indentSize);\n }\n else {\n up_resolveIndents(upLineNumber);\n upLineIndentLevel = this._getIndentLevelForWhitespaceLine(offSide, up_aboveContentLineIndent, up_belowContentLineIndent);\n }\n if (distance === 0) {\n // This is the initial line number\n startLineNumber = upLineNumber;\n endLineNumber = downLineNumber;\n indent = upLineIndentLevel;\n if (indent === 0) {\n // No need to continue\n return { startLineNumber: startLineNumber, endLineNumber: endLineNumber, indent: indent };\n }\n continue;\n }\n if (upLineIndentLevel >= indent) {\n startLineNumber = upLineNumber;\n }\n else {\n goUp = false;\n }\n }\n if (goDown) {\n // compute indent level going down\n var downLineIndentLevel = void 0;\n var currentIndent = this._computeIndentLevel(downLineNumber - 1);\n if (currentIndent >= 0) {\n // This line has content (besides whitespace)\n // Use the line's indent\n down_aboveContentLineIndex = downLineNumber - 1;\n down_aboveContentLineIndent = currentIndent;\n downLineIndentLevel = Math.ceil(currentIndent / this._options.indentSize);\n }\n else {\n down_resolveIndents(downLineNumber);\n downLineIndentLevel = this._getIndentLevelForWhitespaceLine(offSide, down_aboveContentLineIndent, down_belowContentLineIndent);\n }\n if (downLineIndentLevel >= indent) {\n endLineNumber = downLineNumber;\n }\n else {\n goDown = false;\n }\n }\n }\n return { startLineNumber: startLineNumber, endLineNumber: endLineNumber, indent: indent };\n };\n TextModel.prototype.getLinesIndentGuides = function (startLineNumber, endLineNumber) {\n this._assertNotDisposed();\n var lineCount = this.getLineCount();\n if (startLineNumber < 1 || startLineNumber > lineCount) {\n throw new Error('Illegal value for startLineNumber');\n }\n if (endLineNumber < 1 || endLineNumber > lineCount) {\n throw new Error('Illegal value for endLineNumber');\n }\n var foldingRules = LanguageConfigurationRegistry.getFoldingRules(this._languageIdentifier.id);\n var offSide = Boolean(foldingRules && foldingRules.offSide);\n var result = new Array(endLineNumber - startLineNumber + 1);\n var aboveContentLineIndex = -2; /* -2 is a marker for not having computed it */\n var aboveContentLineIndent = -1;\n var belowContentLineIndex = -2; /* -2 is a marker for not having computed it */\n var belowContentLineIndent = -1;\n for (var lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {\n var resultIndex = lineNumber - startLineNumber;\n var currentIndent = this._computeIndentLevel(lineNumber - 1);\n if (currentIndent >= 0) {\n // This line has content (besides whitespace)\n // Use the line's indent\n aboveContentLineIndex = lineNumber - 1;\n aboveContentLineIndent = currentIndent;\n result[resultIndex] = Math.ceil(currentIndent / this._options.indentSize);\n continue;\n }\n if (aboveContentLineIndex === -2) {\n aboveContentLineIndex = -1;\n aboveContentLineIndent = -1;\n // must find previous line with content\n for (var lineIndex = lineNumber - 2; lineIndex >= 0; lineIndex--) {\n var indent = this._computeIndentLevel(lineIndex);\n if (indent >= 0) {\n aboveContentLineIndex = lineIndex;\n aboveContentLineIndent = indent;\n break;\n }\n }\n }\n if (belowContentLineIndex !== -1 && (belowContentLineIndex === -2 || belowContentLineIndex < lineNumber - 1)) {\n belowContentLineIndex = -1;\n belowContentLineIndent = -1;\n // must find next line with content\n for (var lineIndex = lineNumber; lineIndex < lineCount; lineIndex++) {\n var indent = this._computeIndentLevel(lineIndex);\n if (indent >= 0) {\n belowContentLineIndex = lineIndex;\n belowContentLineIndent = indent;\n break;\n }\n }\n }\n result[resultIndex] = this._getIndentLevelForWhitespaceLine(offSide, aboveContentLineIndent, belowContentLineIndent);\n }\n return result;\n };\n TextModel.prototype._getIndentLevelForWhitespaceLine = function (offSide, aboveContentLineIndent, belowContentLineIndent) {\n if (aboveContentLineIndent === -1 || belowContentLineIndent === -1) {\n // At the top or bottom of the file\n return 0;\n }\n else if (aboveContentLineIndent < belowContentLineIndent) {\n // we are inside the region above\n return (1 + Math.floor(aboveContentLineIndent / this._options.indentSize));\n }\n else if (aboveContentLineIndent === belowContentLineIndent) {\n // we are in between two regions\n return Math.ceil(belowContentLineIndent / this._options.indentSize);\n }\n else {\n if (offSide) {\n // same level as region below\n return Math.ceil(belowContentLineIndent / this._options.indentSize);\n }\n else {\n // we are inside the region that ends below\n return (1 + Math.floor(belowContentLineIndent / this._options.indentSize));\n }\n }\n };\n TextModel.MODEL_SYNC_LIMIT = 50 * 1024 * 1024; // 50 MB\n TextModel.LARGE_FILE_SIZE_THRESHOLD = 20 * 1024 * 1024; // 20 MB;\n TextModel.LARGE_FILE_LINE_COUNT_THRESHOLD = 300 * 1000; // 300K lines\n TextModel.DEFAULT_CREATION_OPTIONS = {\n isForSimpleWidget: false,\n tabSize: EDITOR_MODEL_DEFAULTS.tabSize,\n indentSize: EDITOR_MODEL_DEFAULTS.indentSize,\n insertSpaces: EDITOR_MODEL_DEFAULTS.insertSpaces,\n detectIndentation: false,\n defaultEOL: 1 /* LF */,\n trimAutoWhitespace: EDITOR_MODEL_DEFAULTS.trimAutoWhitespace,\n largeFileOptimizations: EDITOR_MODEL_DEFAULTS.largeFileOptimizations,\n };\n return TextModel;\n}(Disposable));\nexport { TextModel };\n//#region Decorations\nvar DecorationsTrees = /** @class */ (function () {\n function DecorationsTrees() {\n this._decorationsTree0 = new IntervalTree();\n this._decorationsTree1 = new IntervalTree();\n }\n DecorationsTrees.prototype.intervalSearch = function (start, end, filterOwnerId, filterOutValidation, cachedVersionId) {\n var r0 = this._decorationsTree0.intervalSearch(start, end, filterOwnerId, filterOutValidation, cachedVersionId);\n var r1 = this._decorationsTree1.intervalSearch(start, end, filterOwnerId, filterOutValidation, cachedVersionId);\n return r0.concat(r1);\n };\n DecorationsTrees.prototype.search = function (filterOwnerId, filterOutValidation, overviewRulerOnly, cachedVersionId) {\n if (overviewRulerOnly) {\n return this._decorationsTree1.search(filterOwnerId, filterOutValidation, cachedVersionId);\n }\n else {\n var r0 = this._decorationsTree0.search(filterOwnerId, filterOutValidation, cachedVersionId);\n var r1 = this._decorationsTree1.search(filterOwnerId, filterOutValidation, cachedVersionId);\n return r0.concat(r1);\n }\n };\n DecorationsTrees.prototype.collectNodesFromOwner = function (ownerId) {\n var r0 = this._decorationsTree0.collectNodesFromOwner(ownerId);\n var r1 = this._decorationsTree1.collectNodesFromOwner(ownerId);\n return r0.concat(r1);\n };\n DecorationsTrees.prototype.collectNodesPostOrder = function () {\n var r0 = this._decorationsTree0.collectNodesPostOrder();\n var r1 = this._decorationsTree1.collectNodesPostOrder();\n return r0.concat(r1);\n };\n DecorationsTrees.prototype.insert = function (node) {\n if (getNodeIsInOverviewRuler(node)) {\n this._decorationsTree1.insert(node);\n }\n else {\n this._decorationsTree0.insert(node);\n }\n };\n DecorationsTrees.prototype.delete = function (node) {\n if (getNodeIsInOverviewRuler(node)) {\n this._decorationsTree1.delete(node);\n }\n else {\n this._decorationsTree0.delete(node);\n }\n };\n DecorationsTrees.prototype.resolveNode = function (node, cachedVersionId) {\n if (getNodeIsInOverviewRuler(node)) {\n this._decorationsTree1.resolveNode(node, cachedVersionId);\n }\n else {\n this._decorationsTree0.resolveNode(node, cachedVersionId);\n }\n };\n DecorationsTrees.prototype.acceptReplace = function (offset, length, textLength, forceMoveMarkers) {\n this._decorationsTree0.acceptReplace(offset, length, textLength, forceMoveMarkers);\n this._decorationsTree1.acceptReplace(offset, length, textLength, forceMoveMarkers);\n };\n return DecorationsTrees;\n}());\nfunction cleanClassName(className) {\n return className.replace(/[^a-z0-9\\-_]/gi, ' ');\n}\nvar ModelDecorationOverviewRulerOptions = /** @class */ (function () {\n function ModelDecorationOverviewRulerOptions(options) {\n this.color = options.color || strings.empty;\n this.darkColor = options.darkColor || strings.empty;\n this.position = (typeof options.position === 'number' ? options.position : model.OverviewRulerLane.Center);\n this._resolvedColor = null;\n }\n ModelDecorationOverviewRulerOptions.prototype.getColor = function (theme) {\n if (!this._resolvedColor) {\n if (theme.type !== 'light' && this.darkColor) {\n this._resolvedColor = this._resolveColor(this.darkColor, theme);\n }\n else {\n this._resolvedColor = this._resolveColor(this.color, theme);\n }\n }\n return this._resolvedColor;\n };\n ModelDecorationOverviewRulerOptions.prototype.invalidateCachedColor = function () {\n this._resolvedColor = null;\n };\n ModelDecorationOverviewRulerOptions.prototype._resolveColor = function (color, theme) {\n if (typeof color === 'string') {\n return color;\n }\n var c = color ? theme.getColor(color.id) : null;\n if (!c) {\n return strings.empty;\n }\n return c.toString();\n };\n return ModelDecorationOverviewRulerOptions;\n}());\nexport { ModelDecorationOverviewRulerOptions };\nvar ModelDecorationOptions = /** @class */ (function () {\n function ModelDecorationOptions(options) {\n this.stickiness = options.stickiness || 0 /* AlwaysGrowsWhenTypingAtEdges */;\n this.zIndex = options.zIndex || 0;\n this.className = options.className ? cleanClassName(options.className) : null;\n this.hoverMessage = withUndefinedAsNull(options.hoverMessage);\n this.glyphMarginHoverMessage = withUndefinedAsNull(options.glyphMarginHoverMessage);\n this.isWholeLine = options.isWholeLine || false;\n this.showIfCollapsed = options.showIfCollapsed || false;\n this.collapseOnReplaceEdit = options.collapseOnReplaceEdit || false;\n this.overviewRuler = options.overviewRuler ? new ModelDecorationOverviewRulerOptions(options.overviewRuler) : null;\n this.glyphMarginClassName = options.glyphMarginClassName ? cleanClassName(options.glyphMarginClassName) : null;\n this.linesDecorationsClassName = options.linesDecorationsClassName ? cleanClassName(options.linesDecorationsClassName) : null;\n this.marginClassName = options.marginClassName ? cleanClassName(options.marginClassName) : null;\n this.inlineClassName = options.inlineClassName ? cleanClassName(options.inlineClassName) : null;\n this.inlineClassNameAffectsLetterSpacing = options.inlineClassNameAffectsLetterSpacing || false;\n this.beforeContentClassName = options.beforeContentClassName ? cleanClassName(options.beforeContentClassName) : null;\n this.afterContentClassName = options.afterContentClassName ? cleanClassName(options.afterContentClassName) : null;\n }\n ModelDecorationOptions.register = function (options) {\n return new ModelDecorationOptions(options);\n };\n ModelDecorationOptions.createDynamic = function (options) {\n return new ModelDecorationOptions(options);\n };\n return ModelDecorationOptions;\n}());\nexport { ModelDecorationOptions };\nModelDecorationOptions.EMPTY = ModelDecorationOptions.register({});\n/**\n * The order carefully matches the values of the enum.\n */\nvar TRACKED_RANGE_OPTIONS = [\n ModelDecorationOptions.register({ stickiness: 0 /* AlwaysGrowsWhenTypingAtEdges */ }),\n ModelDecorationOptions.register({ stickiness: 1 /* NeverGrowsWhenTypingAtEdges */ }),\n ModelDecorationOptions.register({ stickiness: 2 /* GrowsOnlyWhenTypingBefore */ }),\n ModelDecorationOptions.register({ stickiness: 3 /* GrowsOnlyWhenTypingAfter */ }),\n];\nfunction _normalizeOptions(options) {\n if (options instanceof ModelDecorationOptions) {\n return options;\n }\n return ModelDecorationOptions.createDynamic(options);\n}\nvar DidChangeDecorationsEmitter = /** @class */ (function (_super) {\n __extends(DidChangeDecorationsEmitter, _super);\n function DidChangeDecorationsEmitter() {\n var _this = _super.call(this) || this;\n _this._actual = _this._register(new Emitter());\n _this.event = _this._actual.event;\n _this._deferredCnt = 0;\n _this._shouldFire = false;\n return _this;\n }\n DidChangeDecorationsEmitter.prototype.beginDeferredEmit = function () {\n this._deferredCnt++;\n };\n DidChangeDecorationsEmitter.prototype.endDeferredEmit = function () {\n this._deferredCnt--;\n if (this._deferredCnt === 0) {\n if (this._shouldFire) {\n this._shouldFire = false;\n this._actual.fire({});\n }\n }\n };\n DidChangeDecorationsEmitter.prototype.fire = function () {\n this._shouldFire = true;\n };\n return DidChangeDecorationsEmitter;\n}(Disposable));\nexport { DidChangeDecorationsEmitter };\n//#endregion\nvar DidChangeContentEmitter = /** @class */ (function (_super) {\n __extends(DidChangeContentEmitter, _super);\n function DidChangeContentEmitter() {\n var _this = _super.call(this) || this;\n /**\n * Both `fastEvent` and `slowEvent` work the same way and contain the same events, but first we invoke `fastEvent` and then `slowEvent`.\n */\n _this._fastEmitter = _this._register(new Emitter());\n _this.fastEvent = _this._fastEmitter.event;\n _this._slowEmitter = _this._register(new Emitter());\n _this.slowEvent = _this._slowEmitter.event;\n _this._deferredCnt = 0;\n _this._deferredEvent = null;\n return _this;\n }\n DidChangeContentEmitter.prototype.beginDeferredEmit = function () {\n this._deferredCnt++;\n };\n DidChangeContentEmitter.prototype.endDeferredEmit = function () {\n this._deferredCnt--;\n if (this._deferredCnt === 0) {\n if (this._deferredEvent !== null) {\n var e = this._deferredEvent;\n this._deferredEvent = null;\n this._fastEmitter.fire(e);\n this._slowEmitter.fire(e);\n }\n }\n };\n DidChangeContentEmitter.prototype.fire = function (e) {\n if (this._deferredCnt > 0) {\n if (this._deferredEvent) {\n this._deferredEvent = this._deferredEvent.merge(e);\n }\n else {\n this._deferredEvent = e;\n }\n return;\n }\n this._fastEmitter.fire(e);\n this._slowEmitter.fire(e);\n };\n return DidChangeContentEmitter;\n}(Disposable));\nexport { DidChangeContentEmitter };\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport { onUnexpectedError } from '../../../base/common/errors.js';\nimport * as strings from '../../../base/common/strings.js';\nimport { Position } from '../core/position.js';\nimport { Range } from '../core/range.js';\nimport { Selection } from '../core/selection.js';\nimport { TextModel } from '../model/textModel.js';\nimport { LanguageConfigurationRegistry } from '../modes/languageConfigurationRegistry.js';\nvar autoCloseAlways = function () { return true; };\nvar autoCloseNever = function () { return false; };\nvar autoCloseBeforeWhitespace = function (chr) { return (chr === ' ' || chr === '\\t'); };\nvar CursorConfiguration = /** @class */ (function () {\n function CursorConfiguration(languageIdentifier, modelOptions, configuration) {\n this._languageIdentifier = languageIdentifier;\n var c = configuration.editor;\n this.readOnly = c.readOnly;\n this.tabSize = modelOptions.tabSize;\n this.indentSize = modelOptions.indentSize;\n this.insertSpaces = modelOptions.insertSpaces;\n this.pageSize = Math.max(1, Math.floor(c.layoutInfo.height / c.fontInfo.lineHeight) - 2);\n this.lineHeight = c.lineHeight;\n this.useTabStops = c.useTabStops;\n this.wordSeparators = c.wordSeparators;\n this.emptySelectionClipboard = c.emptySelectionClipboard;\n this.copyWithSyntaxHighlighting = c.copyWithSyntaxHighlighting;\n this.multiCursorMergeOverlapping = c.multiCursorMergeOverlapping;\n this.autoClosingBrackets = c.autoClosingBrackets;\n this.autoClosingQuotes = c.autoClosingQuotes;\n this.autoSurround = c.autoSurround;\n this.autoIndent = c.autoIndent;\n this.autoClosingPairsOpen = {};\n this.autoClosingPairsClose = {};\n this.surroundingPairs = {};\n this._electricChars = null;\n this.shouldAutoCloseBefore = {\n quote: CursorConfiguration._getShouldAutoClose(languageIdentifier, this.autoClosingQuotes),\n bracket: CursorConfiguration._getShouldAutoClose(languageIdentifier, this.autoClosingBrackets)\n };\n var autoClosingPairs = CursorConfiguration._getAutoClosingPairs(languageIdentifier);\n if (autoClosingPairs) {\n for (var _i = 0, autoClosingPairs_1 = autoClosingPairs; _i < autoClosingPairs_1.length; _i++) {\n var pair = autoClosingPairs_1[_i];\n this.autoClosingPairsOpen[pair.open] = pair.close;\n this.autoClosingPairsClose[pair.close] = pair.open;\n }\n }\n var surroundingPairs = CursorConfiguration._getSurroundingPairs(languageIdentifier);\n if (surroundingPairs) {\n for (var _a = 0, surroundingPairs_1 = surroundingPairs; _a < surroundingPairs_1.length; _a++) {\n var pair = surroundingPairs_1[_a];\n this.surroundingPairs[pair.open] = pair.close;\n }\n }\n }\n CursorConfiguration.shouldRecreate = function (e) {\n return (e.layoutInfo\n || e.wordSeparators\n || e.emptySelectionClipboard\n || e.multiCursorMergeOverlapping\n || e.autoClosingBrackets\n || e.autoClosingQuotes\n || e.autoSurround\n || e.useTabStops\n || e.lineHeight\n || e.readOnly);\n };\n Object.defineProperty(CursorConfiguration.prototype, \"electricChars\", {\n get: function () {\n if (!this._electricChars) {\n this._electricChars = {};\n var electricChars = CursorConfiguration._getElectricCharacters(this._languageIdentifier);\n if (electricChars) {\n for (var _i = 0, electricChars_1 = electricChars; _i < electricChars_1.length; _i++) {\n var char = electricChars_1[_i];\n this._electricChars[char] = true;\n }\n }\n }\n return this._electricChars;\n },\n enumerable: true,\n configurable: true\n });\n CursorConfiguration.prototype.normalizeIndentation = function (str) {\n return TextModel.normalizeIndentation(str, this.indentSize, this.insertSpaces);\n };\n CursorConfiguration._getElectricCharacters = function (languageIdentifier) {\n try {\n return LanguageConfigurationRegistry.getElectricCharacters(languageIdentifier.id);\n }\n catch (e) {\n onUnexpectedError(e);\n return null;\n }\n };\n CursorConfiguration._getAutoClosingPairs = function (languageIdentifier) {\n try {\n return LanguageConfigurationRegistry.getAutoClosingPairs(languageIdentifier.id);\n }\n catch (e) {\n onUnexpectedError(e);\n return null;\n }\n };\n CursorConfiguration._getShouldAutoClose = function (languageIdentifier, autoCloseConfig) {\n switch (autoCloseConfig) {\n case 'beforeWhitespace':\n return autoCloseBeforeWhitespace;\n case 'languageDefined':\n return CursorConfiguration._getLanguageDefinedShouldAutoClose(languageIdentifier);\n case 'always':\n return autoCloseAlways;\n case 'never':\n return autoCloseNever;\n }\n };\n CursorConfiguration._getLanguageDefinedShouldAutoClose = function (languageIdentifier) {\n try {\n var autoCloseBeforeSet_1 = LanguageConfigurationRegistry.getAutoCloseBeforeSet(languageIdentifier.id);\n return function (c) { return autoCloseBeforeSet_1.indexOf(c) !== -1; };\n }\n catch (e) {\n onUnexpectedError(e);\n return autoCloseNever;\n }\n };\n CursorConfiguration._getSurroundingPairs = function (languageIdentifier) {\n try {\n return LanguageConfigurationRegistry.getSurroundingPairs(languageIdentifier.id);\n }\n catch (e) {\n onUnexpectedError(e);\n return null;\n }\n };\n return CursorConfiguration;\n}());\nexport { CursorConfiguration };\n/**\n * Represents the cursor state on either the model or on the view model.\n */\nvar SingleCursorState = /** @class */ (function () {\n function SingleCursorState(selectionStart, selectionStartLeftoverVisibleColumns, position, leftoverVisibleColumns) {\n this.selectionStart = selectionStart;\n this.selectionStartLeftoverVisibleColumns = selectionStartLeftoverVisibleColumns;\n this.position = position;\n this.leftoverVisibleColumns = leftoverVisibleColumns;\n this.selection = SingleCursorState._computeSelection(this.selectionStart, this.position);\n }\n SingleCursorState.prototype.equals = function (other) {\n return (this.selectionStartLeftoverVisibleColumns === other.selectionStartLeftoverVisibleColumns\n && this.leftoverVisibleColumns === other.leftoverVisibleColumns\n && this.position.equals(other.position)\n && this.selectionStart.equalsRange(other.selectionStart));\n };\n SingleCursorState.prototype.hasSelection = function () {\n return (!this.selection.isEmpty() || !this.selectionStart.isEmpty());\n };\n SingleCursorState.prototype.move = function (inSelectionMode, lineNumber, column, leftoverVisibleColumns) {\n if (inSelectionMode) {\n // move just position\n return new SingleCursorState(this.selectionStart, this.selectionStartLeftoverVisibleColumns, new Position(lineNumber, column), leftoverVisibleColumns);\n }\n else {\n // move everything\n return new SingleCursorState(new Range(lineNumber, column, lineNumber, column), leftoverVisibleColumns, new Position(lineNumber, column), leftoverVisibleColumns);\n }\n };\n SingleCursorState._computeSelection = function (selectionStart, position) {\n var startLineNumber, startColumn, endLineNumber, endColumn;\n if (selectionStart.isEmpty()) {\n startLineNumber = selectionStart.startLineNumber;\n startColumn = selectionStart.startColumn;\n endLineNumber = position.lineNumber;\n endColumn = position.column;\n }\n else {\n if (position.isBeforeOrEqual(selectionStart.getStartPosition())) {\n startLineNumber = selectionStart.endLineNumber;\n startColumn = selectionStart.endColumn;\n endLineNumber = position.lineNumber;\n endColumn = position.column;\n }\n else {\n startLineNumber = selectionStart.startLineNumber;\n startColumn = selectionStart.startColumn;\n endLineNumber = position.lineNumber;\n endColumn = position.column;\n }\n }\n return new Selection(startLineNumber, startColumn, endLineNumber, endColumn);\n };\n return SingleCursorState;\n}());\nexport { SingleCursorState };\nvar CursorContext = /** @class */ (function () {\n function CursorContext(configuration, model, viewModel) {\n this.model = model;\n this.viewModel = viewModel;\n this.config = new CursorConfiguration(this.model.getLanguageIdentifier(), this.model.getOptions(), configuration);\n }\n CursorContext.prototype.validateViewPosition = function (viewPosition, modelPosition) {\n return this.viewModel.coordinatesConverter.validateViewPosition(viewPosition, modelPosition);\n };\n CursorContext.prototype.validateViewRange = function (viewRange, expectedModelRange) {\n return this.viewModel.coordinatesConverter.validateViewRange(viewRange, expectedModelRange);\n };\n CursorContext.prototype.convertViewRangeToModelRange = function (viewRange) {\n return this.viewModel.coordinatesConverter.convertViewRangeToModelRange(viewRange);\n };\n CursorContext.prototype.convertViewPositionToModelPosition = function (lineNumber, column) {\n return this.viewModel.coordinatesConverter.convertViewPositionToModelPosition(new Position(lineNumber, column));\n };\n CursorContext.prototype.convertModelPositionToViewPosition = function (modelPosition) {\n return this.viewModel.coordinatesConverter.convertModelPositionToViewPosition(modelPosition);\n };\n CursorContext.prototype.convertModelRangeToViewRange = function (modelRange) {\n return this.viewModel.coordinatesConverter.convertModelRangeToViewRange(modelRange);\n };\n CursorContext.prototype.getCurrentScrollTop = function () {\n return this.viewModel.viewLayout.getCurrentScrollTop();\n };\n CursorContext.prototype.getCompletelyVisibleViewRange = function () {\n return this.viewModel.getCompletelyVisibleViewRange();\n };\n CursorContext.prototype.getCompletelyVisibleModelRange = function () {\n var viewRange = this.viewModel.getCompletelyVisibleViewRange();\n return this.viewModel.coordinatesConverter.convertViewRangeToModelRange(viewRange);\n };\n CursorContext.prototype.getCompletelyVisibleViewRangeAtScrollTop = function (scrollTop) {\n return this.viewModel.getCompletelyVisibleViewRangeAtScrollTop(scrollTop);\n };\n CursorContext.prototype.getVerticalOffsetForViewLine = function (viewLineNumber) {\n return this.viewModel.viewLayout.getVerticalOffsetForLineNumber(viewLineNumber);\n };\n return CursorContext;\n}());\nexport { CursorContext };\nvar PartialModelCursorState = /** @class */ (function () {\n function PartialModelCursorState(modelState) {\n this.modelState = modelState;\n this.viewState = null;\n }\n return PartialModelCursorState;\n}());\nexport { PartialModelCursorState };\nvar PartialViewCursorState = /** @class */ (function () {\n function PartialViewCursorState(viewState) {\n this.modelState = null;\n this.viewState = viewState;\n }\n return PartialViewCursorState;\n}());\nexport { PartialViewCursorState };\nvar CursorState = /** @class */ (function () {\n function CursorState(modelState, viewState) {\n this.modelState = modelState;\n this.viewState = viewState;\n }\n CursorState.fromModelState = function (modelState) {\n return new PartialModelCursorState(modelState);\n };\n CursorState.fromViewState = function (viewState) {\n return new PartialViewCursorState(viewState);\n };\n CursorState.fromModelSelection = function (modelSelection) {\n var selectionStartLineNumber = modelSelection.selectionStartLineNumber;\n var selectionStartColumn = modelSelection.selectionStartColumn;\n var positionLineNumber = modelSelection.positionLineNumber;\n var positionColumn = modelSelection.positionColumn;\n var modelState = new SingleCursorState(new Range(selectionStartLineNumber, selectionStartColumn, selectionStartLineNumber, selectionStartColumn), 0, new Position(positionLineNumber, positionColumn), 0);\n return CursorState.fromModelState(modelState);\n };\n CursorState.fromModelSelections = function (modelSelections) {\n var states = [];\n for (var i = 0, len = modelSelections.length; i < len; i++) {\n states[i] = this.fromModelSelection(modelSelections[i]);\n }\n return states;\n };\n CursorState.prototype.equals = function (other) {\n return (this.viewState.equals(other.viewState) && this.modelState.equals(other.modelState));\n };\n return CursorState;\n}());\nexport { CursorState };\nvar EditOperationResult = /** @class */ (function () {\n function EditOperationResult(type, commands, opts) {\n this.type = type;\n this.commands = commands;\n this.shouldPushStackElementBefore = opts.shouldPushStackElementBefore;\n this.shouldPushStackElementAfter = opts.shouldPushStackElementAfter;\n }\n return EditOperationResult;\n}());\nexport { EditOperationResult };\n/**\n * Common operations that work and make sense both on the model and on the view model.\n */\nvar CursorColumns = /** @class */ (function () {\n function CursorColumns() {\n }\n CursorColumns.isLowSurrogate = function (model, lineNumber, charOffset) {\n var lineContent = model.getLineContent(lineNumber);\n if (charOffset < 0 || charOffset >= lineContent.length) {\n return false;\n }\n return strings.isLowSurrogate(lineContent.charCodeAt(charOffset));\n };\n CursorColumns.isHighSurrogate = function (model, lineNumber, charOffset) {\n var lineContent = model.getLineContent(lineNumber);\n if (charOffset < 0 || charOffset >= lineContent.length) {\n return false;\n }\n return strings.isHighSurrogate(lineContent.charCodeAt(charOffset));\n };\n CursorColumns.isInsideSurrogatePair = function (model, lineNumber, column) {\n return this.isHighSurrogate(model, lineNumber, column - 2);\n };\n CursorColumns.visibleColumnFromColumn = function (lineContent, column, tabSize) {\n var endOffset = lineContent.length;\n if (endOffset > column - 1) {\n endOffset = column - 1;\n }\n var result = 0;\n for (var i = 0; i < endOffset; i++) {\n var charCode = lineContent.charCodeAt(i);\n if (charCode === 9 /* Tab */) {\n result = this.nextRenderTabStop(result, tabSize);\n }\n else if (strings.isFullWidthCharacter(charCode)) {\n result = result + 2;\n }\n else {\n result = result + 1;\n }\n }\n return result;\n };\n CursorColumns.visibleColumnFromColumn2 = function (config, model, position) {\n return this.visibleColumnFromColumn(model.getLineContent(position.lineNumber), position.column, config.tabSize);\n };\n CursorColumns.columnFromVisibleColumn = function (lineContent, visibleColumn, tabSize) {\n if (visibleColumn <= 0) {\n return 1;\n }\n var lineLength = lineContent.length;\n var beforeVisibleColumn = 0;\n for (var i = 0; i < lineLength; i++) {\n var charCode = lineContent.charCodeAt(i);\n var afterVisibleColumn = void 0;\n if (charCode === 9 /* Tab */) {\n afterVisibleColumn = this.nextRenderTabStop(beforeVisibleColumn, tabSize);\n }\n else if (strings.isFullWidthCharacter(charCode)) {\n afterVisibleColumn = beforeVisibleColumn + 2;\n }\n else {\n afterVisibleColumn = beforeVisibleColumn + 1;\n }\n if (afterVisibleColumn >= visibleColumn) {\n var prevDelta = visibleColumn - beforeVisibleColumn;\n var afterDelta = afterVisibleColumn - visibleColumn;\n if (afterDelta < prevDelta) {\n return i + 2;\n }\n else {\n return i + 1;\n }\n }\n beforeVisibleColumn = afterVisibleColumn;\n }\n // walked the entire string\n return lineLength + 1;\n };\n CursorColumns.columnFromVisibleColumn2 = function (config, model, lineNumber, visibleColumn) {\n var result = this.columnFromVisibleColumn(model.getLineContent(lineNumber), visibleColumn, config.tabSize);\n var minColumn = model.getLineMinColumn(lineNumber);\n if (result < minColumn) {\n return minColumn;\n }\n var maxColumn = model.getLineMaxColumn(lineNumber);\n if (result > maxColumn) {\n return maxColumn;\n }\n return result;\n };\n /**\n * ATTENTION: This works with 0-based columns (as oposed to the regular 1-based columns)\n */\n CursorColumns.nextRenderTabStop = function (visibleColumn, tabSize) {\n return visibleColumn + tabSize - visibleColumn % tabSize;\n };\n /**\n * ATTENTION: This works with 0-based columns (as oposed to the regular 1-based columns)\n */\n CursorColumns.nextIndentTabStop = function (visibleColumn, indentSize) {\n return visibleColumn + indentSize - visibleColumn % indentSize;\n };\n /**\n * ATTENTION: This works with 0-based columns (as oposed to the regular 1-based columns)\n */\n CursorColumns.prevRenderTabStop = function (column, tabSize) {\n return column - 1 - (column - 1) % tabSize;\n };\n /**\n * ATTENTION: This works with 0-based columns (as oposed to the regular 1-based columns)\n */\n CursorColumns.prevIndentTabStop = function (column, indentSize) {\n return column - 1 - (column - 1) % indentSize;\n };\n return CursorColumns;\n}());\nexport { CursorColumns };\nexport function isQuote(ch) {\n return (ch === '\\'' || ch === '\"' || ch === '`');\n}\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport { CursorColumns, SingleCursorState } from './cursorCommon.js';\nimport { Position } from '../core/position.js';\nimport { Range } from '../core/range.js';\nvar ColumnSelection = /** @class */ (function () {\n function ColumnSelection() {\n }\n ColumnSelection._columnSelect = function (config, model, fromLineNumber, fromVisibleColumn, toLineNumber, toVisibleColumn) {\n var lineCount = Math.abs(toLineNumber - fromLineNumber) + 1;\n var reversed = (fromLineNumber > toLineNumber);\n var isRTL = (fromVisibleColumn > toVisibleColumn);\n var isLTR = (fromVisibleColumn < toVisibleColumn);\n var result = [];\n // console.log(`fromVisibleColumn: ${fromVisibleColumn}, toVisibleColumn: ${toVisibleColumn}`);\n for (var i = 0; i < lineCount; i++) {\n var lineNumber = fromLineNumber + (reversed ? -i : i);\n var startColumn = CursorColumns.columnFromVisibleColumn2(config, model, lineNumber, fromVisibleColumn);\n var endColumn = CursorColumns.columnFromVisibleColumn2(config, model, lineNumber, toVisibleColumn);\n var visibleStartColumn = CursorColumns.visibleColumnFromColumn2(config, model, new Position(lineNumber, startColumn));\n var visibleEndColumn = CursorColumns.visibleColumnFromColumn2(config, model, new Position(lineNumber, endColumn));\n // console.log(`lineNumber: ${lineNumber}: visibleStartColumn: ${visibleStartColumn}, visibleEndColumn: ${visibleEndColumn}`);\n if (isLTR) {\n if (visibleStartColumn > toVisibleColumn) {\n continue;\n }\n if (visibleEndColumn < fromVisibleColumn) {\n continue;\n }\n }\n if (isRTL) {\n if (visibleEndColumn > fromVisibleColumn) {\n continue;\n }\n if (visibleStartColumn < toVisibleColumn) {\n continue;\n }\n }\n result.push(new SingleCursorState(new Range(lineNumber, startColumn, lineNumber, startColumn), 0, new Position(lineNumber, endColumn), 0));\n }\n return {\n viewStates: result,\n reversed: reversed,\n toLineNumber: toLineNumber,\n toVisualColumn: toVisibleColumn\n };\n };\n ColumnSelection.columnSelect = function (config, model, fromViewSelection, toViewLineNumber, toViewVisualColumn) {\n var fromViewPosition = new Position(fromViewSelection.selectionStartLineNumber, fromViewSelection.selectionStartColumn);\n var fromViewVisibleColumn = CursorColumns.visibleColumnFromColumn2(config, model, fromViewPosition);\n return ColumnSelection._columnSelect(config, model, fromViewPosition.lineNumber, fromViewVisibleColumn, toViewLineNumber, toViewVisualColumn);\n };\n ColumnSelection.columnSelectLeft = function (config, model, cursor, toViewLineNumber, toViewVisualColumn) {\n if (toViewVisualColumn > 1) {\n toViewVisualColumn--;\n }\n return this.columnSelect(config, model, cursor.selection, toViewLineNumber, toViewVisualColumn);\n };\n ColumnSelection.columnSelectRight = function (config, model, cursor, toViewLineNumber, toViewVisualColumn) {\n var maxVisualViewColumn = 0;\n var minViewLineNumber = Math.min(cursor.position.lineNumber, toViewLineNumber);\n var maxViewLineNumber = Math.max(cursor.position.lineNumber, toViewLineNumber);\n for (var lineNumber = minViewLineNumber; lineNumber <= maxViewLineNumber; lineNumber++) {\n var lineMaxViewColumn = model.getLineMaxColumn(lineNumber);\n var lineMaxVisualViewColumn = CursorColumns.visibleColumnFromColumn2(config, model, new Position(lineNumber, lineMaxViewColumn));\n maxVisualViewColumn = Math.max(maxVisualViewColumn, lineMaxVisualViewColumn);\n }\n if (toViewVisualColumn < maxVisualViewColumn) {\n toViewVisualColumn++;\n }\n return this.columnSelect(config, model, cursor.selection, toViewLineNumber, toViewVisualColumn);\n };\n ColumnSelection.columnSelectUp = function (config, model, cursor, isPaged, toViewLineNumber, toViewVisualColumn) {\n var linesCount = isPaged ? config.pageSize : 1;\n toViewLineNumber -= linesCount;\n if (toViewLineNumber < 1) {\n toViewLineNumber = 1;\n }\n return this.columnSelect(config, model, cursor.selection, toViewLineNumber, toViewVisualColumn);\n };\n ColumnSelection.columnSelectDown = function (config, model, cursor, isPaged, toViewLineNumber, toViewVisualColumn) {\n var linesCount = isPaged ? config.pageSize : 1;\n toViewLineNumber += linesCount;\n if (toViewLineNumber > model.getLineCount()) {\n toViewLineNumber = model.getLineCount();\n }\n return this.columnSelect(config, model, cursor.selection, toViewLineNumber, toViewVisualColumn);\n };\n return ColumnSelection;\n}());\nexport { ColumnSelection };\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport { Selection } from '../core/selection.js';\nvar ReplaceCommand = /** @class */ (function () {\n function ReplaceCommand(range, text, insertsAutoWhitespace) {\n if (insertsAutoWhitespace === void 0) { insertsAutoWhitespace = false; }\n this._range = range;\n this._text = text;\n this.insertsAutoWhitespace = insertsAutoWhitespace;\n }\n ReplaceCommand.prototype.getEditOperations = function (model, builder) {\n builder.addTrackedEditOperation(this._range, this._text);\n };\n ReplaceCommand.prototype.computeCursorState = function (model, helper) {\n var inverseEditOperations = helper.getInverseEditOperations();\n var srcRange = inverseEditOperations[0].range;\n return new Selection(srcRange.endLineNumber, srcRange.endColumn, srcRange.endLineNumber, srcRange.endColumn);\n };\n return ReplaceCommand;\n}());\nexport { ReplaceCommand };\nvar ReplaceCommandWithoutChangingPosition = /** @class */ (function () {\n function ReplaceCommandWithoutChangingPosition(range, text, insertsAutoWhitespace) {\n if (insertsAutoWhitespace === void 0) { insertsAutoWhitespace = false; }\n this._range = range;\n this._text = text;\n this.insertsAutoWhitespace = insertsAutoWhitespace;\n }\n ReplaceCommandWithoutChangingPosition.prototype.getEditOperations = function (model, builder) {\n builder.addTrackedEditOperation(this._range, this._text);\n };\n ReplaceCommandWithoutChangingPosition.prototype.computeCursorState = function (model, helper) {\n var inverseEditOperations = helper.getInverseEditOperations();\n var srcRange = inverseEditOperations[0].range;\n return new Selection(srcRange.startLineNumber, srcRange.startColumn, srcRange.startLineNumber, srcRange.startColumn);\n };\n return ReplaceCommandWithoutChangingPosition;\n}());\nexport { ReplaceCommandWithoutChangingPosition };\nvar ReplaceCommandWithOffsetCursorState = /** @class */ (function () {\n function ReplaceCommandWithOffsetCursorState(range, text, lineNumberDeltaOffset, columnDeltaOffset, insertsAutoWhitespace) {\n if (insertsAutoWhitespace === void 0) { insertsAutoWhitespace = false; }\n this._range = range;\n this._text = text;\n this._columnDeltaOffset = columnDeltaOffset;\n this._lineNumberDeltaOffset = lineNumberDeltaOffset;\n this.insertsAutoWhitespace = insertsAutoWhitespace;\n }\n ReplaceCommandWithOffsetCursorState.prototype.getEditOperations = function (model, builder) {\n builder.addTrackedEditOperation(this._range, this._text);\n };\n ReplaceCommandWithOffsetCursorState.prototype.computeCursorState = function (model, helper) {\n var inverseEditOperations = helper.getInverseEditOperations();\n var srcRange = inverseEditOperations[0].range;\n return new Selection(srcRange.endLineNumber + this._lineNumberDeltaOffset, srcRange.endColumn + this._columnDeltaOffset, srcRange.endLineNumber + this._lineNumberDeltaOffset, srcRange.endColumn + this._columnDeltaOffset);\n };\n return ReplaceCommandWithOffsetCursorState;\n}());\nexport { ReplaceCommandWithOffsetCursorState };\nvar ReplaceCommandThatPreservesSelection = /** @class */ (function () {\n function ReplaceCommandThatPreservesSelection(editRange, text, initialSelection) {\n this._range = editRange;\n this._text = text;\n this._initialSelection = initialSelection;\n }\n ReplaceCommandThatPreservesSelection.prototype.getEditOperations = function (model, builder) {\n builder.addEditOperation(this._range, this._text);\n this._selectionId = builder.trackSelection(this._initialSelection);\n };\n ReplaceCommandThatPreservesSelection.prototype.computeCursorState = function (model, helper) {\n return helper.getTrackedSelection(this._selectionId);\n };\n return ReplaceCommandThatPreservesSelection;\n}());\nexport { ReplaceCommandThatPreservesSelection };\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport { CursorColumns, SingleCursorState } from './cursorCommon.js';\nimport { Position } from '../core/position.js';\nimport { Range } from '../core/range.js';\nvar CursorPosition = /** @class */ (function () {\n function CursorPosition(lineNumber, column, leftoverVisibleColumns) {\n this.lineNumber = lineNumber;\n this.column = column;\n this.leftoverVisibleColumns = leftoverVisibleColumns;\n }\n return CursorPosition;\n}());\nexport { CursorPosition };\nvar MoveOperations = /** @class */ (function () {\n function MoveOperations() {\n }\n MoveOperations.left = function (config, model, lineNumber, column) {\n if (column > model.getLineMinColumn(lineNumber)) {\n if (CursorColumns.isLowSurrogate(model, lineNumber, column - 2)) {\n // character before column is a low surrogate\n column = column - 2;\n }\n else {\n column = column - 1;\n }\n }\n else if (lineNumber > 1) {\n lineNumber = lineNumber - 1;\n column = model.getLineMaxColumn(lineNumber);\n }\n return new CursorPosition(lineNumber, column, 0);\n };\n MoveOperations.moveLeft = function (config, model, cursor, inSelectionMode, noOfColumns) {\n var lineNumber, column;\n if (cursor.hasSelection() && !inSelectionMode) {\n // If we are in selection mode, move left without selection cancels selection and puts cursor at the beginning of the selection\n lineNumber = cursor.selection.startLineNumber;\n column = cursor.selection.startColumn;\n }\n else {\n var r = MoveOperations.left(config, model, cursor.position.lineNumber, cursor.position.column - (noOfColumns - 1));\n lineNumber = r.lineNumber;\n column = r.column;\n }\n return cursor.move(inSelectionMode, lineNumber, column, 0);\n };\n MoveOperations.right = function (config, model, lineNumber, column) {\n if (column < model.getLineMaxColumn(lineNumber)) {\n if (CursorColumns.isHighSurrogate(model, lineNumber, column - 1)) {\n // character after column is a high surrogate\n column = column + 2;\n }\n else {\n column = column + 1;\n }\n }\n else if (lineNumber < model.getLineCount()) {\n lineNumber = lineNumber + 1;\n column = model.getLineMinColumn(lineNumber);\n }\n return new CursorPosition(lineNumber, column, 0);\n };\n MoveOperations.moveRight = function (config, model, cursor, inSelectionMode, noOfColumns) {\n var lineNumber, column;\n if (cursor.hasSelection() && !inSelectionMode) {\n // If we are in selection mode, move right without selection cancels selection and puts cursor at the end of the selection\n lineNumber = cursor.selection.endLineNumber;\n column = cursor.selection.endColumn;\n }\n else {\n var r = MoveOperations.right(config, model, cursor.position.lineNumber, cursor.position.column + (noOfColumns - 1));\n lineNumber = r.lineNumber;\n column = r.column;\n }\n return cursor.move(inSelectionMode, lineNumber, column, 0);\n };\n MoveOperations.down = function (config, model, lineNumber, column, leftoverVisibleColumns, count, allowMoveOnLastLine) {\n var currentVisibleColumn = CursorColumns.visibleColumnFromColumn(model.getLineContent(lineNumber), column, config.tabSize) + leftoverVisibleColumns;\n lineNumber = lineNumber + count;\n var lineCount = model.getLineCount();\n if (lineNumber > lineCount) {\n lineNumber = lineCount;\n if (allowMoveOnLastLine) {\n column = model.getLineMaxColumn(lineNumber);\n }\n else {\n column = Math.min(model.getLineMaxColumn(lineNumber), column);\n if (CursorColumns.isInsideSurrogatePair(model, lineNumber, column)) {\n column = column - 1;\n }\n }\n }\n else {\n column = CursorColumns.columnFromVisibleColumn2(config, model, lineNumber, currentVisibleColumn);\n if (CursorColumns.isInsideSurrogatePair(model, lineNumber, column)) {\n column = column - 1;\n }\n }\n leftoverVisibleColumns = currentVisibleColumn - CursorColumns.visibleColumnFromColumn(model.getLineContent(lineNumber), column, config.tabSize);\n return new CursorPosition(lineNumber, column, leftoverVisibleColumns);\n };\n MoveOperations.moveDown = function (config, model, cursor, inSelectionMode, linesCount) {\n var lineNumber, column;\n if (cursor.hasSelection() && !inSelectionMode) {\n // If we are in selection mode, move down acts relative to the end of selection\n lineNumber = cursor.selection.endLineNumber;\n column = cursor.selection.endColumn;\n }\n else {\n lineNumber = cursor.position.lineNumber;\n column = cursor.position.column;\n }\n var r = MoveOperations.down(config, model, lineNumber, column, cursor.leftoverVisibleColumns, linesCount, true);\n return cursor.move(inSelectionMode, r.lineNumber, r.column, r.leftoverVisibleColumns);\n };\n MoveOperations.translateDown = function (config, model, cursor) {\n var selection = cursor.selection;\n var selectionStart = MoveOperations.down(config, model, selection.selectionStartLineNumber, selection.selectionStartColumn, cursor.selectionStartLeftoverVisibleColumns, 1, false);\n var position = MoveOperations.down(config, model, selection.positionLineNumber, selection.positionColumn, cursor.leftoverVisibleColumns, 1, false);\n return new SingleCursorState(new Range(selectionStart.lineNumber, selectionStart.column, selectionStart.lineNumber, selectionStart.column), selectionStart.leftoverVisibleColumns, new Position(position.lineNumber, position.column), position.leftoverVisibleColumns);\n };\n MoveOperations.up = function (config, model, lineNumber, column, leftoverVisibleColumns, count, allowMoveOnFirstLine) {\n var currentVisibleColumn = CursorColumns.visibleColumnFromColumn(model.getLineContent(lineNumber), column, config.tabSize) + leftoverVisibleColumns;\n lineNumber = lineNumber - count;\n if (lineNumber < 1) {\n lineNumber = 1;\n if (allowMoveOnFirstLine) {\n column = model.getLineMinColumn(lineNumber);\n }\n else {\n column = Math.min(model.getLineMaxColumn(lineNumber), column);\n if (CursorColumns.isInsideSurrogatePair(model, lineNumber, column)) {\n column = column - 1;\n }\n }\n }\n else {\n column = CursorColumns.columnFromVisibleColumn2(config, model, lineNumber, currentVisibleColumn);\n if (CursorColumns.isInsideSurrogatePair(model, lineNumber, column)) {\n column = column - 1;\n }\n }\n leftoverVisibleColumns = currentVisibleColumn - CursorColumns.visibleColumnFromColumn(model.getLineContent(lineNumber), column, config.tabSize);\n return new CursorPosition(lineNumber, column, leftoverVisibleColumns);\n };\n MoveOperations.moveUp = function (config, model, cursor, inSelectionMode, linesCount) {\n var lineNumber, column;\n if (cursor.hasSelection() && !inSelectionMode) {\n // If we are in selection mode, move up acts relative to the beginning of selection\n lineNumber = cursor.selection.startLineNumber;\n column = cursor.selection.startColumn;\n }\n else {\n lineNumber = cursor.position.lineNumber;\n column = cursor.position.column;\n }\n var r = MoveOperations.up(config, model, lineNumber, column, cursor.leftoverVisibleColumns, linesCount, true);\n return cursor.move(inSelectionMode, r.lineNumber, r.column, r.leftoverVisibleColumns);\n };\n MoveOperations.translateUp = function (config, model, cursor) {\n var selection = cursor.selection;\n var selectionStart = MoveOperations.up(config, model, selection.selectionStartLineNumber, selection.selectionStartColumn, cursor.selectionStartLeftoverVisibleColumns, 1, false);\n var position = MoveOperations.up(config, model, selection.positionLineNumber, selection.positionColumn, cursor.leftoverVisibleColumns, 1, false);\n return new SingleCursorState(new Range(selectionStart.lineNumber, selectionStart.column, selectionStart.lineNumber, selectionStart.column), selectionStart.leftoverVisibleColumns, new Position(position.lineNumber, position.column), position.leftoverVisibleColumns);\n };\n MoveOperations.moveToBeginningOfLine = function (config, model, cursor, inSelectionMode) {\n var lineNumber = cursor.position.lineNumber;\n var minColumn = model.getLineMinColumn(lineNumber);\n var firstNonBlankColumn = model.getLineFirstNonWhitespaceColumn(lineNumber) || minColumn;\n var column;\n var relevantColumnNumber = cursor.position.column;\n if (relevantColumnNumber === firstNonBlankColumn) {\n column = minColumn;\n }\n else {\n column = firstNonBlankColumn;\n }\n return cursor.move(inSelectionMode, lineNumber, column, 0);\n };\n MoveOperations.moveToEndOfLine = function (config, model, cursor, inSelectionMode) {\n var lineNumber = cursor.position.lineNumber;\n var maxColumn = model.getLineMaxColumn(lineNumber);\n return cursor.move(inSelectionMode, lineNumber, maxColumn, 0);\n };\n MoveOperations.moveToBeginningOfBuffer = function (config, model, cursor, inSelectionMode) {\n return cursor.move(inSelectionMode, 1, 1, 0);\n };\n MoveOperations.moveToEndOfBuffer = function (config, model, cursor, inSelectionMode) {\n var lastLineNumber = model.getLineCount();\n var lastColumn = model.getLineMaxColumn(lastLineNumber);\n return cursor.move(inSelectionMode, lastLineNumber, lastColumn, 0);\n };\n return MoveOperations;\n}());\nexport { MoveOperations };\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport * as strings from '../../../base/common/strings.js';\nimport { ReplaceCommand } from '../commands/replaceCommand.js';\nimport { CursorColumns, EditOperationResult, isQuote } from './cursorCommon.js';\nimport { MoveOperations } from './cursorMoveOperations.js';\nimport { Range } from '../core/range.js';\nvar DeleteOperations = /** @class */ (function () {\n function DeleteOperations() {\n }\n DeleteOperations.deleteRight = function (prevEditOperationType, config, model, selections) {\n var commands = [];\n var shouldPushStackElementBefore = (prevEditOperationType !== 3 /* DeletingRight */);\n for (var i = 0, len = selections.length; i < len; i++) {\n var selection = selections[i];\n var deleteSelection = selection;\n if (deleteSelection.isEmpty()) {\n var position = selection.getPosition();\n var rightOfPosition = MoveOperations.right(config, model, position.lineNumber, position.column);\n deleteSelection = new Range(rightOfPosition.lineNumber, rightOfPosition.column, position.lineNumber, position.column);\n }\n if (deleteSelection.isEmpty()) {\n // Probably at end of file => ignore\n commands[i] = null;\n continue;\n }\n if (deleteSelection.startLineNumber !== deleteSelection.endLineNumber) {\n shouldPushStackElementBefore = true;\n }\n commands[i] = new ReplaceCommand(deleteSelection, '');\n }\n return [shouldPushStackElementBefore, commands];\n };\n DeleteOperations._isAutoClosingPairDelete = function (config, model, selections) {\n if (config.autoClosingBrackets === 'never' && config.autoClosingQuotes === 'never') {\n return false;\n }\n for (var i = 0, len = selections.length; i < len; i++) {\n var selection = selections[i];\n var position = selection.getPosition();\n if (!selection.isEmpty()) {\n return false;\n }\n var lineText = model.getLineContent(position.lineNumber);\n var character = lineText[position.column - 2];\n if (!config.autoClosingPairsOpen.hasOwnProperty(character)) {\n return false;\n }\n if (isQuote(character)) {\n if (config.autoClosingQuotes === 'never') {\n return false;\n }\n }\n else {\n if (config.autoClosingBrackets === 'never') {\n return false;\n }\n }\n var afterCharacter = lineText[position.column - 1];\n var closeCharacter = config.autoClosingPairsOpen[character];\n if (afterCharacter !== closeCharacter) {\n return false;\n }\n }\n return true;\n };\n DeleteOperations._runAutoClosingPairDelete = function (config, model, selections) {\n var commands = [];\n for (var i = 0, len = selections.length; i < len; i++) {\n var position = selections[i].getPosition();\n var deleteSelection = new Range(position.lineNumber, position.column - 1, position.lineNumber, position.column + 1);\n commands[i] = new ReplaceCommand(deleteSelection, '');\n }\n return [true, commands];\n };\n DeleteOperations.deleteLeft = function (prevEditOperationType, config, model, selections) {\n if (this._isAutoClosingPairDelete(config, model, selections)) {\n return this._runAutoClosingPairDelete(config, model, selections);\n }\n var commands = [];\n var shouldPushStackElementBefore = (prevEditOperationType !== 2 /* DeletingLeft */);\n for (var i = 0, len = selections.length; i < len; i++) {\n var selection = selections[i];\n var deleteSelection = selection;\n if (deleteSelection.isEmpty()) {\n var position = selection.getPosition();\n if (config.useTabStops && position.column > 1) {\n var lineContent = model.getLineContent(position.lineNumber);\n var firstNonWhitespaceIndex = strings.firstNonWhitespaceIndex(lineContent);\n var lastIndentationColumn = (firstNonWhitespaceIndex === -1\n ? /* entire string is whitespace */ lineContent.length + 1\n : firstNonWhitespaceIndex + 1);\n if (position.column <= lastIndentationColumn) {\n var fromVisibleColumn = CursorColumns.visibleColumnFromColumn2(config, model, position);\n var toVisibleColumn = CursorColumns.prevIndentTabStop(fromVisibleColumn, config.indentSize);\n var toColumn = CursorColumns.columnFromVisibleColumn2(config, model, position.lineNumber, toVisibleColumn);\n deleteSelection = new Range(position.lineNumber, toColumn, position.lineNumber, position.column);\n }\n else {\n deleteSelection = new Range(position.lineNumber, position.column - 1, position.lineNumber, position.column);\n }\n }\n else {\n var leftOfPosition = MoveOperations.left(config, model, position.lineNumber, position.column);\n deleteSelection = new Range(leftOfPosition.lineNumber, leftOfPosition.column, position.lineNumber, position.column);\n }\n }\n if (deleteSelection.isEmpty()) {\n // Probably at beginning of file => ignore\n commands[i] = null;\n continue;\n }\n if (deleteSelection.startLineNumber !== deleteSelection.endLineNumber) {\n shouldPushStackElementBefore = true;\n }\n commands[i] = new ReplaceCommand(deleteSelection, '');\n }\n return [shouldPushStackElementBefore, commands];\n };\n DeleteOperations.cut = function (config, model, selections) {\n var commands = [];\n for (var i = 0, len = selections.length; i < len; i++) {\n var selection = selections[i];\n if (selection.isEmpty()) {\n if (config.emptySelectionClipboard) {\n // This is a full line cut\n var position = selection.getPosition();\n var startLineNumber = void 0, startColumn = void 0, endLineNumber = void 0, endColumn = void 0;\n if (position.lineNumber < model.getLineCount()) {\n // Cutting a line in the middle of the model\n startLineNumber = position.lineNumber;\n startColumn = 1;\n endLineNumber = position.lineNumber + 1;\n endColumn = 1;\n }\n else if (position.lineNumber > 1) {\n // Cutting the last line & there are more than 1 lines in the model\n startLineNumber = position.lineNumber - 1;\n startColumn = model.getLineMaxColumn(position.lineNumber - 1);\n endLineNumber = position.lineNumber;\n endColumn = model.getLineMaxColumn(position.lineNumber);\n }\n else {\n // Cutting the single line that the model contains\n startLineNumber = position.lineNumber;\n startColumn = 1;\n endLineNumber = position.lineNumber;\n endColumn = model.getLineMaxColumn(position.lineNumber);\n }\n var deleteSelection = new Range(startLineNumber, startColumn, endLineNumber, endColumn);\n if (!deleteSelection.isEmpty()) {\n commands[i] = new ReplaceCommand(deleteSelection, '');\n }\n else {\n commands[i] = null;\n }\n }\n else {\n // Cannot cut empty selection\n commands[i] = null;\n }\n }\n else {\n commands[i] = new ReplaceCommand(selection, '');\n }\n }\n return new EditOperationResult(0 /* Other */, commands, {\n shouldPushStackElementBefore: true,\n shouldPushStackElementAfter: true\n });\n };\n return DeleteOperations;\n}());\nexport { DeleteOperations };\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport * as strings from '../../../base/common/strings.js';\nimport { SingleCursorState } from './cursorCommon.js';\nimport { getMapForWordSeparators } from './wordCharacterClassifier.js';\nimport { Position } from '../core/position.js';\nimport { Range } from '../core/range.js';\nvar WordOperations = /** @class */ (function () {\n function WordOperations() {\n }\n WordOperations._createWord = function (lineContent, wordType, nextCharClass, start, end) {\n // console.log('WORD ==> ' + start + ' => ' + end + ':::: <<<' + lineContent.substring(start, end) + '>>>');\n return { start: start, end: end, wordType: wordType, nextCharClass: nextCharClass };\n };\n WordOperations._findPreviousWordOnLine = function (wordSeparators, model, position) {\n var lineContent = model.getLineContent(position.lineNumber);\n return this._doFindPreviousWordOnLine(lineContent, wordSeparators, position);\n };\n WordOperations._doFindPreviousWordOnLine = function (lineContent, wordSeparators, position) {\n var wordType = 0 /* None */;\n for (var chIndex = position.column - 2; chIndex >= 0; chIndex--) {\n var chCode = lineContent.charCodeAt(chIndex);\n var chClass = wordSeparators.get(chCode);\n if (chClass === 0 /* Regular */) {\n if (wordType === 2 /* Separator */) {\n return this._createWord(lineContent, wordType, chClass, chIndex + 1, this._findEndOfWord(lineContent, wordSeparators, wordType, chIndex + 1));\n }\n wordType = 1 /* Regular */;\n }\n else if (chClass === 2 /* WordSeparator */) {\n if (wordType === 1 /* Regular */) {\n return this._createWord(lineContent, wordType, chClass, chIndex + 1, this._findEndOfWord(lineContent, wordSeparators, wordType, chIndex + 1));\n }\n wordType = 2 /* Separator */;\n }\n else if (chClass === 1 /* Whitespace */) {\n if (wordType !== 0 /* None */) {\n return this._createWord(lineContent, wordType, chClass, chIndex + 1, this._findEndOfWord(lineContent, wordSeparators, wordType, chIndex + 1));\n }\n }\n }\n if (wordType !== 0 /* None */) {\n return this._createWord(lineContent, wordType, 1 /* Whitespace */, 0, this._findEndOfWord(lineContent, wordSeparators, wordType, 0));\n }\n return null;\n };\n WordOperations._findEndOfWord = function (lineContent, wordSeparators, wordType, startIndex) {\n var len = lineContent.length;\n for (var chIndex = startIndex; chIndex < len; chIndex++) {\n var chCode = lineContent.charCodeAt(chIndex);\n var chClass = wordSeparators.get(chCode);\n if (chClass === 1 /* Whitespace */) {\n return chIndex;\n }\n if (wordType === 1 /* Regular */ && chClass === 2 /* WordSeparator */) {\n return chIndex;\n }\n if (wordType === 2 /* Separator */ && chClass === 0 /* Regular */) {\n return chIndex;\n }\n }\n return len;\n };\n WordOperations._findNextWordOnLine = function (wordSeparators, model, position) {\n var lineContent = model.getLineContent(position.lineNumber);\n return this._doFindNextWordOnLine(lineContent, wordSeparators, position);\n };\n WordOperations._doFindNextWordOnLine = function (lineContent, wordSeparators, position) {\n var wordType = 0 /* None */;\n var len = lineContent.length;\n for (var chIndex = position.column - 1; chIndex < len; chIndex++) {\n var chCode = lineContent.charCodeAt(chIndex);\n var chClass = wordSeparators.get(chCode);\n if (chClass === 0 /* Regular */) {\n if (wordType === 2 /* Separator */) {\n return this._createWord(lineContent, wordType, chClass, this._findStartOfWord(lineContent, wordSeparators, wordType, chIndex - 1), chIndex);\n }\n wordType = 1 /* Regular */;\n }\n else if (chClass === 2 /* WordSeparator */) {\n if (wordType === 1 /* Regular */) {\n return this._createWord(lineContent, wordType, chClass, this._findStartOfWord(lineContent, wordSeparators, wordType, chIndex - 1), chIndex);\n }\n wordType = 2 /* Separator */;\n }\n else if (chClass === 1 /* Whitespace */) {\n if (wordType !== 0 /* None */) {\n return this._createWord(lineContent, wordType, chClass, this._findStartOfWord(lineContent, wordSeparators, wordType, chIndex - 1), chIndex);\n }\n }\n }\n if (wordType !== 0 /* None */) {\n return this._createWord(lineContent, wordType, 1 /* Whitespace */, this._findStartOfWord(lineContent, wordSeparators, wordType, len - 1), len);\n }\n return null;\n };\n WordOperations._findStartOfWord = function (lineContent, wordSeparators, wordType, startIndex) {\n for (var chIndex = startIndex; chIndex >= 0; chIndex--) {\n var chCode = lineContent.charCodeAt(chIndex);\n var chClass = wordSeparators.get(chCode);\n if (chClass === 1 /* Whitespace */) {\n return chIndex + 1;\n }\n if (wordType === 1 /* Regular */ && chClass === 2 /* WordSeparator */) {\n return chIndex + 1;\n }\n if (wordType === 2 /* Separator */ && chClass === 0 /* Regular */) {\n return chIndex + 1;\n }\n }\n return 0;\n };\n WordOperations.moveWordLeft = function (wordSeparators, model, position, wordNavigationType) {\n var lineNumber = position.lineNumber;\n var column = position.column;\n var movedToPreviousLine = false;\n if (column === 1) {\n if (lineNumber > 1) {\n movedToPreviousLine = true;\n lineNumber = lineNumber - 1;\n column = model.getLineMaxColumn(lineNumber);\n }\n }\n var prevWordOnLine = WordOperations._findPreviousWordOnLine(wordSeparators, model, new Position(lineNumber, column));\n if (wordNavigationType === 0 /* WordStart */) {\n if (prevWordOnLine && !movedToPreviousLine) {\n // Special case for Visual Studio compatibility:\n // when starting in the trim whitespace at the end of a line,\n // go to the end of the last word\n var lastWhitespaceColumn = model.getLineLastNonWhitespaceColumn(lineNumber);\n if (lastWhitespaceColumn < column) {\n return new Position(lineNumber, prevWordOnLine.end + 1);\n }\n }\n return new Position(lineNumber, prevWordOnLine ? prevWordOnLine.start + 1 : 1);\n }\n if (wordNavigationType === 1 /* WordStartFast */) {\n if (prevWordOnLine\n && prevWordOnLine.wordType === 2 /* Separator */\n && prevWordOnLine.end - prevWordOnLine.start === 1\n && prevWordOnLine.nextCharClass === 0 /* Regular */) {\n // Skip over a word made up of one single separator and followed by a regular character\n prevWordOnLine = WordOperations._findPreviousWordOnLine(wordSeparators, model, new Position(lineNumber, prevWordOnLine.start + 1));\n }\n return new Position(lineNumber, prevWordOnLine ? prevWordOnLine.start + 1 : 1);\n }\n // We are stopping at the ending of words\n if (prevWordOnLine && column <= prevWordOnLine.end + 1) {\n prevWordOnLine = WordOperations._findPreviousWordOnLine(wordSeparators, model, new Position(lineNumber, prevWordOnLine.start + 1));\n }\n return new Position(lineNumber, prevWordOnLine ? prevWordOnLine.end + 1 : 1);\n };\n WordOperations._moveWordPartLeft = function (model, position) {\n var lineNumber = position.lineNumber;\n var maxColumn = model.getLineMaxColumn(lineNumber);\n if (position.column === 1) {\n return (lineNumber > 1 ? new Position(lineNumber - 1, model.getLineMaxColumn(lineNumber - 1)) : position);\n }\n var lineContent = model.getLineContent(lineNumber);\n for (var column = position.column - 1; column > 1; column--) {\n var left = lineContent.charCodeAt(column - 2);\n var right = lineContent.charCodeAt(column - 1);\n if (left !== 95 /* Underline */ && right === 95 /* Underline */) {\n // snake_case_variables\n return new Position(lineNumber, column);\n }\n if (strings.isLowerAsciiLetter(left) && strings.isUpperAsciiLetter(right)) {\n // camelCaseVariables\n return new Position(lineNumber, column);\n }\n if (strings.isUpperAsciiLetter(left) && strings.isUpperAsciiLetter(right)) {\n // thisIsACamelCaseWithOneLetterWords\n if (column + 1 < maxColumn) {\n var rightRight = lineContent.charCodeAt(column);\n if (strings.isLowerAsciiLetter(rightRight)) {\n return new Position(lineNumber, column);\n }\n }\n }\n }\n return new Position(lineNumber, 1);\n };\n WordOperations.moveWordRight = function (wordSeparators, model, position, wordNavigationType) {\n var lineNumber = position.lineNumber;\n var column = position.column;\n var movedDown = false;\n if (column === model.getLineMaxColumn(lineNumber)) {\n if (lineNumber < model.getLineCount()) {\n movedDown = true;\n lineNumber = lineNumber + 1;\n column = 1;\n }\n }\n var nextWordOnLine = WordOperations._findNextWordOnLine(wordSeparators, model, new Position(lineNumber, column));\n if (wordNavigationType === 2 /* WordEnd */) {\n if (nextWordOnLine && nextWordOnLine.wordType === 2 /* Separator */) {\n if (nextWordOnLine.end - nextWordOnLine.start === 1 && nextWordOnLine.nextCharClass === 0 /* Regular */) {\n // Skip over a word made up of one single separator and followed by a regular character\n nextWordOnLine = WordOperations._findNextWordOnLine(wordSeparators, model, new Position(lineNumber, nextWordOnLine.end + 1));\n }\n }\n if (nextWordOnLine) {\n column = nextWordOnLine.end + 1;\n }\n else {\n column = model.getLineMaxColumn(lineNumber);\n }\n }\n else {\n if (nextWordOnLine && !movedDown && column >= nextWordOnLine.start + 1) {\n nextWordOnLine = WordOperations._findNextWordOnLine(wordSeparators, model, new Position(lineNumber, nextWordOnLine.end + 1));\n }\n if (nextWordOnLine) {\n column = nextWordOnLine.start + 1;\n }\n else {\n column = model.getLineMaxColumn(lineNumber);\n }\n }\n return new Position(lineNumber, column);\n };\n WordOperations._moveWordPartRight = function (model, position) {\n var lineNumber = position.lineNumber;\n var maxColumn = model.getLineMaxColumn(lineNumber);\n if (position.column === maxColumn) {\n return (lineNumber < model.getLineCount() ? new Position(lineNumber + 1, 1) : position);\n }\n var lineContent = model.getLineContent(lineNumber);\n for (var column = position.column + 1; column < maxColumn; column++) {\n var left = lineContent.charCodeAt(column - 2);\n var right = lineContent.charCodeAt(column - 1);\n if (left === 95 /* Underline */ && right !== 95 /* Underline */) {\n // snake_case_variables\n return new Position(lineNumber, column);\n }\n if (strings.isLowerAsciiLetter(left) && strings.isUpperAsciiLetter(right)) {\n // camelCaseVariables\n return new Position(lineNumber, column);\n }\n if (strings.isUpperAsciiLetter(left) && strings.isUpperAsciiLetter(right)) {\n // thisIsACamelCaseWithOneLetterWords\n if (column + 1 < maxColumn) {\n var rightRight = lineContent.charCodeAt(column);\n if (strings.isLowerAsciiLetter(rightRight)) {\n return new Position(lineNumber, column);\n }\n }\n }\n }\n return new Position(lineNumber, maxColumn);\n };\n WordOperations._deleteWordLeftWhitespace = function (model, position) {\n var lineContent = model.getLineContent(position.lineNumber);\n var startIndex = position.column - 2;\n var lastNonWhitespace = strings.lastNonWhitespaceIndex(lineContent, startIndex);\n if (lastNonWhitespace + 1 < startIndex) {\n return new Range(position.lineNumber, lastNonWhitespace + 2, position.lineNumber, position.column);\n }\n return null;\n };\n WordOperations.deleteWordLeft = function (wordSeparators, model, selection, whitespaceHeuristics, wordNavigationType) {\n if (!selection.isEmpty()) {\n return selection;\n }\n var position = new Position(selection.positionLineNumber, selection.positionColumn);\n var lineNumber = position.lineNumber;\n var column = position.column;\n if (lineNumber === 1 && column === 1) {\n // Ignore deleting at beginning of file\n return null;\n }\n if (whitespaceHeuristics) {\n var r = this._deleteWordLeftWhitespace(model, position);\n if (r) {\n return r;\n }\n }\n var prevWordOnLine = WordOperations._findPreviousWordOnLine(wordSeparators, model, position);\n if (wordNavigationType === 0 /* WordStart */) {\n if (prevWordOnLine) {\n column = prevWordOnLine.start + 1;\n }\n else {\n if (column > 1) {\n column = 1;\n }\n else {\n lineNumber--;\n column = model.getLineMaxColumn(lineNumber);\n }\n }\n }\n else {\n if (prevWordOnLine && column <= prevWordOnLine.end + 1) {\n prevWordOnLine = WordOperations._findPreviousWordOnLine(wordSeparators, model, new Position(lineNumber, prevWordOnLine.start + 1));\n }\n if (prevWordOnLine) {\n column = prevWordOnLine.end + 1;\n }\n else {\n if (column > 1) {\n column = 1;\n }\n else {\n lineNumber--;\n column = model.getLineMaxColumn(lineNumber);\n }\n }\n }\n return new Range(lineNumber, column, position.lineNumber, position.column);\n };\n WordOperations._deleteWordPartLeft = function (model, selection) {\n if (!selection.isEmpty()) {\n return selection;\n }\n var pos = selection.getPosition();\n var toPosition = WordOperations._moveWordPartLeft(model, pos);\n return new Range(pos.lineNumber, pos.column, toPosition.lineNumber, toPosition.column);\n };\n WordOperations._findFirstNonWhitespaceChar = function (str, startIndex) {\n var len = str.length;\n for (var chIndex = startIndex; chIndex < len; chIndex++) {\n var ch = str.charAt(chIndex);\n if (ch !== ' ' && ch !== '\\t') {\n return chIndex;\n }\n }\n return len;\n };\n WordOperations._deleteWordRightWhitespace = function (model, position) {\n var lineContent = model.getLineContent(position.lineNumber);\n var startIndex = position.column - 1;\n var firstNonWhitespace = this._findFirstNonWhitespaceChar(lineContent, startIndex);\n if (startIndex + 1 < firstNonWhitespace) {\n // bingo\n return new Range(position.lineNumber, position.column, position.lineNumber, firstNonWhitespace + 1);\n }\n return null;\n };\n WordOperations.deleteWordRight = function (wordSeparators, model, selection, whitespaceHeuristics, wordNavigationType) {\n if (!selection.isEmpty()) {\n return selection;\n }\n var position = new Position(selection.positionLineNumber, selection.positionColumn);\n var lineNumber = position.lineNumber;\n var column = position.column;\n var lineCount = model.getLineCount();\n var maxColumn = model.getLineMaxColumn(lineNumber);\n if (lineNumber === lineCount && column === maxColumn) {\n // Ignore deleting at end of file\n return null;\n }\n if (whitespaceHeuristics) {\n var r = this._deleteWordRightWhitespace(model, position);\n if (r) {\n return r;\n }\n }\n var nextWordOnLine = WordOperations._findNextWordOnLine(wordSeparators, model, position);\n if (wordNavigationType === 2 /* WordEnd */) {\n if (nextWordOnLine) {\n column = nextWordOnLine.end + 1;\n }\n else {\n if (column < maxColumn || lineNumber === lineCount) {\n column = maxColumn;\n }\n else {\n lineNumber++;\n nextWordOnLine = WordOperations._findNextWordOnLine(wordSeparators, model, new Position(lineNumber, 1));\n if (nextWordOnLine) {\n column = nextWordOnLine.start + 1;\n }\n else {\n column = model.getLineMaxColumn(lineNumber);\n }\n }\n }\n }\n else {\n if (nextWordOnLine && column >= nextWordOnLine.start + 1) {\n nextWordOnLine = WordOperations._findNextWordOnLine(wordSeparators, model, new Position(lineNumber, nextWordOnLine.end + 1));\n }\n if (nextWordOnLine) {\n column = nextWordOnLine.start + 1;\n }\n else {\n if (column < maxColumn || lineNumber === lineCount) {\n column = maxColumn;\n }\n else {\n lineNumber++;\n nextWordOnLine = WordOperations._findNextWordOnLine(wordSeparators, model, new Position(lineNumber, 1));\n if (nextWordOnLine) {\n column = nextWordOnLine.start + 1;\n }\n else {\n column = model.getLineMaxColumn(lineNumber);\n }\n }\n }\n }\n return new Range(lineNumber, column, position.lineNumber, position.column);\n };\n WordOperations._deleteWordPartRight = function (model, selection) {\n if (!selection.isEmpty()) {\n return selection;\n }\n var pos = selection.getPosition();\n var toPosition = WordOperations._moveWordPartRight(model, pos);\n return new Range(pos.lineNumber, pos.column, toPosition.lineNumber, toPosition.column);\n };\n WordOperations.word = function (config, model, cursor, inSelectionMode, position) {\n var wordSeparators = getMapForWordSeparators(config.wordSeparators);\n var prevWord = WordOperations._findPreviousWordOnLine(wordSeparators, model, position);\n var nextWord = WordOperations._findNextWordOnLine(wordSeparators, model, position);\n if (!inSelectionMode) {\n // Entering word selection for the first time\n var startColumn_1;\n var endColumn_1;\n if (prevWord && prevWord.wordType === 1 /* Regular */ && prevWord.start <= position.column - 1 && position.column - 1 <= prevWord.end) {\n // isTouchingPrevWord\n startColumn_1 = prevWord.start + 1;\n endColumn_1 = prevWord.end + 1;\n }\n else if (nextWord && nextWord.wordType === 1 /* Regular */ && nextWord.start <= position.column - 1 && position.column - 1 <= nextWord.end) {\n // isTouchingNextWord\n startColumn_1 = nextWord.start + 1;\n endColumn_1 = nextWord.end + 1;\n }\n else {\n if (prevWord) {\n startColumn_1 = prevWord.end + 1;\n }\n else {\n startColumn_1 = 1;\n }\n if (nextWord) {\n endColumn_1 = nextWord.start + 1;\n }\n else {\n endColumn_1 = model.getLineMaxColumn(position.lineNumber);\n }\n }\n return new SingleCursorState(new Range(position.lineNumber, startColumn_1, position.lineNumber, endColumn_1), 0, new Position(position.lineNumber, endColumn_1), 0);\n }\n var startColumn;\n var endColumn;\n if (prevWord && prevWord.wordType === 1 /* Regular */ && prevWord.start < position.column - 1 && position.column - 1 < prevWord.end) {\n // isInsidePrevWord\n startColumn = prevWord.start + 1;\n endColumn = prevWord.end + 1;\n }\n else if (nextWord && nextWord.wordType === 1 /* Regular */ && nextWord.start < position.column - 1 && position.column - 1 < nextWord.end) {\n // isInsideNextWord\n startColumn = nextWord.start + 1;\n endColumn = nextWord.end + 1;\n }\n else {\n startColumn = position.column;\n endColumn = position.column;\n }\n var lineNumber = position.lineNumber;\n var column;\n if (cursor.selectionStart.containsPosition(position)) {\n column = cursor.selectionStart.endColumn;\n }\n else if (position.isBeforeOrEqual(cursor.selectionStart.getStartPosition())) {\n column = startColumn;\n var possiblePosition = new Position(lineNumber, column);\n if (cursor.selectionStart.containsPosition(possiblePosition)) {\n column = cursor.selectionStart.endColumn;\n }\n }\n else {\n column = endColumn;\n var possiblePosition = new Position(lineNumber, column);\n if (cursor.selectionStart.containsPosition(possiblePosition)) {\n column = cursor.selectionStart.startColumn;\n }\n }\n return cursor.move(true, lineNumber, column, 0);\n };\n return WordOperations;\n}());\nexport { WordOperations };\nvar WordPartOperations = /** @class */ (function (_super) {\n __extends(WordPartOperations, _super);\n function WordPartOperations() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n WordPartOperations.deleteWordPartLeft = function (wordSeparators, model, selection, whitespaceHeuristics) {\n var candidates = enforceDefined([\n WordOperations.deleteWordLeft(wordSeparators, model, selection, whitespaceHeuristics, 0 /* WordStart */),\n WordOperations.deleteWordLeft(wordSeparators, model, selection, whitespaceHeuristics, 2 /* WordEnd */),\n WordOperations._deleteWordPartLeft(model, selection)\n ]);\n candidates.sort(Range.compareRangesUsingEnds);\n return candidates[2];\n };\n WordPartOperations.deleteWordPartRight = function (wordSeparators, model, selection, whitespaceHeuristics) {\n var candidates = enforceDefined([\n WordOperations.deleteWordRight(wordSeparators, model, selection, whitespaceHeuristics, 0 /* WordStart */),\n WordOperations.deleteWordRight(wordSeparators, model, selection, whitespaceHeuristics, 2 /* WordEnd */),\n WordOperations._deleteWordPartRight(model, selection)\n ]);\n candidates.sort(Range.compareRangesUsingStarts);\n return candidates[0];\n };\n WordPartOperations.moveWordPartLeft = function (wordSeparators, model, position) {\n var candidates = enforceDefined([\n WordOperations.moveWordLeft(wordSeparators, model, position, 0 /* WordStart */),\n WordOperations.moveWordLeft(wordSeparators, model, position, 2 /* WordEnd */),\n WordOperations._moveWordPartLeft(model, position)\n ]);\n candidates.sort(Position.compare);\n return candidates[2];\n };\n WordPartOperations.moveWordPartRight = function (wordSeparators, model, position) {\n var candidates = enforceDefined([\n WordOperations.moveWordRight(wordSeparators, model, position, 0 /* WordStart */),\n WordOperations.moveWordRight(wordSeparators, model, position, 2 /* WordEnd */),\n WordOperations._moveWordPartRight(model, position)\n ]);\n candidates.sort(Position.compare);\n return candidates[0];\n };\n return WordPartOperations;\n}(WordOperations));\nexport { WordPartOperations };\nfunction enforceDefined(arr) {\n return arr.filter(function (el) { return Boolean(el); });\n}\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport * as types from '../../../base/common/types.js';\nimport { CursorState, SingleCursorState } from './cursorCommon.js';\nimport { MoveOperations } from './cursorMoveOperations.js';\nimport { WordOperations } from './cursorWordOperations.js';\nimport { Position } from '../core/position.js';\nimport { Range } from '../core/range.js';\nvar CursorMoveCommands = /** @class */ (function () {\n function CursorMoveCommands() {\n }\n CursorMoveCommands.addCursorDown = function (context, cursors, useLogicalLine) {\n var result = [], resultLen = 0;\n for (var i = 0, len = cursors.length; i < len; i++) {\n var cursor = cursors[i];\n result[resultLen++] = new CursorState(cursor.modelState, cursor.viewState);\n if (useLogicalLine) {\n result[resultLen++] = CursorState.fromModelState(MoveOperations.translateDown(context.config, context.model, cursor.modelState));\n }\n else {\n result[resultLen++] = CursorState.fromViewState(MoveOperations.translateDown(context.config, context.viewModel, cursor.viewState));\n }\n }\n return result;\n };\n CursorMoveCommands.addCursorUp = function (context, cursors, useLogicalLine) {\n var result = [], resultLen = 0;\n for (var i = 0, len = cursors.length; i < len; i++) {\n var cursor = cursors[i];\n result[resultLen++] = new CursorState(cursor.modelState, cursor.viewState);\n if (useLogicalLine) {\n result[resultLen++] = CursorState.fromModelState(MoveOperations.translateUp(context.config, context.model, cursor.modelState));\n }\n else {\n result[resultLen++] = CursorState.fromViewState(MoveOperations.translateUp(context.config, context.viewModel, cursor.viewState));\n }\n }\n return result;\n };\n CursorMoveCommands.moveToBeginningOfLine = function (context, cursors, inSelectionMode) {\n var result = [];\n for (var i = 0, len = cursors.length; i < len; i++) {\n var cursor = cursors[i];\n result[i] = this._moveToLineStart(context, cursor, inSelectionMode);\n }\n return result;\n };\n CursorMoveCommands._moveToLineStart = function (context, cursor, inSelectionMode) {\n var currentViewStateColumn = cursor.viewState.position.column;\n var currentModelStateColumn = cursor.modelState.position.column;\n var isFirstLineOfWrappedLine = currentViewStateColumn === currentModelStateColumn;\n var currentViewStatelineNumber = cursor.viewState.position.lineNumber;\n var firstNonBlankColumn = context.viewModel.getLineFirstNonWhitespaceColumn(currentViewStatelineNumber);\n var isBeginningOfViewLine = currentViewStateColumn === firstNonBlankColumn;\n if (!isFirstLineOfWrappedLine && !isBeginningOfViewLine) {\n return this._moveToLineStartByView(context, cursor, inSelectionMode);\n }\n else {\n return this._moveToLineStartByModel(context, cursor, inSelectionMode);\n }\n };\n CursorMoveCommands._moveToLineStartByView = function (context, cursor, inSelectionMode) {\n return CursorState.fromViewState(MoveOperations.moveToBeginningOfLine(context.config, context.viewModel, cursor.viewState, inSelectionMode));\n };\n CursorMoveCommands._moveToLineStartByModel = function (context, cursor, inSelectionMode) {\n return CursorState.fromModelState(MoveOperations.moveToBeginningOfLine(context.config, context.model, cursor.modelState, inSelectionMode));\n };\n CursorMoveCommands.moveToEndOfLine = function (context, cursors, inSelectionMode) {\n var result = [];\n for (var i = 0, len = cursors.length; i < len; i++) {\n var cursor = cursors[i];\n result[i] = this._moveToLineEnd(context, cursor, inSelectionMode);\n }\n return result;\n };\n CursorMoveCommands._moveToLineEnd = function (context, cursor, inSelectionMode) {\n var viewStatePosition = cursor.viewState.position;\n var viewModelMaxColumn = context.viewModel.getLineMaxColumn(viewStatePosition.lineNumber);\n var isEndOfViewLine = viewStatePosition.column === viewModelMaxColumn;\n var modelStatePosition = cursor.modelState.position;\n var modelMaxColumn = context.model.getLineMaxColumn(modelStatePosition.lineNumber);\n var isEndLineOfWrappedLine = viewModelMaxColumn - viewStatePosition.column === modelMaxColumn - modelStatePosition.column;\n if (isEndOfViewLine || isEndLineOfWrappedLine) {\n return this._moveToLineEndByModel(context, cursor, inSelectionMode);\n }\n else {\n return this._moveToLineEndByView(context, cursor, inSelectionMode);\n }\n };\n CursorMoveCommands._moveToLineEndByView = function (context, cursor, inSelectionMode) {\n return CursorState.fromViewState(MoveOperations.moveToEndOfLine(context.config, context.viewModel, cursor.viewState, inSelectionMode));\n };\n CursorMoveCommands._moveToLineEndByModel = function (context, cursor, inSelectionMode) {\n return CursorState.fromModelState(MoveOperations.moveToEndOfLine(context.config, context.model, cursor.modelState, inSelectionMode));\n };\n CursorMoveCommands.expandLineSelection = function (context, cursors) {\n var result = [];\n for (var i = 0, len = cursors.length; i < len; i++) {\n var cursor = cursors[i];\n var viewSelection = cursor.viewState.selection;\n var startLineNumber = viewSelection.startLineNumber;\n var lineCount = context.viewModel.getLineCount();\n var endLineNumber = viewSelection.endLineNumber;\n var endColumn = void 0;\n if (endLineNumber === lineCount) {\n endColumn = context.viewModel.getLineMaxColumn(lineCount);\n }\n else {\n endLineNumber++;\n endColumn = 1;\n }\n result[i] = CursorState.fromViewState(new SingleCursorState(new Range(startLineNumber, 1, startLineNumber, 1), 0, new Position(endLineNumber, endColumn), 0));\n }\n return result;\n };\n CursorMoveCommands.moveToBeginningOfBuffer = function (context, cursors, inSelectionMode) {\n var result = [];\n for (var i = 0, len = cursors.length; i < len; i++) {\n var cursor = cursors[i];\n result[i] = CursorState.fromModelState(MoveOperations.moveToBeginningOfBuffer(context.config, context.model, cursor.modelState, inSelectionMode));\n }\n return result;\n };\n CursorMoveCommands.moveToEndOfBuffer = function (context, cursors, inSelectionMode) {\n var result = [];\n for (var i = 0, len = cursors.length; i < len; i++) {\n var cursor = cursors[i];\n result[i] = CursorState.fromModelState(MoveOperations.moveToEndOfBuffer(context.config, context.model, cursor.modelState, inSelectionMode));\n }\n return result;\n };\n CursorMoveCommands.selectAll = function (context, cursor) {\n var lineCount = context.model.getLineCount();\n var maxColumn = context.model.getLineMaxColumn(lineCount);\n return CursorState.fromModelState(new SingleCursorState(new Range(1, 1, 1, 1), 0, new Position(lineCount, maxColumn), 0));\n };\n CursorMoveCommands.line = function (context, cursor, inSelectionMode, _position, _viewPosition) {\n var position = context.model.validatePosition(_position);\n var viewPosition = (_viewPosition\n ? context.validateViewPosition(new Position(_viewPosition.lineNumber, _viewPosition.column), position)\n : context.convertModelPositionToViewPosition(position));\n if (!inSelectionMode || !cursor.modelState.hasSelection()) {\n // Entering line selection for the first time\n var lineCount = context.model.getLineCount();\n var selectToLineNumber = position.lineNumber + 1;\n var selectToColumn = 1;\n if (selectToLineNumber > lineCount) {\n selectToLineNumber = lineCount;\n selectToColumn = context.model.getLineMaxColumn(selectToLineNumber);\n }\n return CursorState.fromModelState(new SingleCursorState(new Range(position.lineNumber, 1, selectToLineNumber, selectToColumn), 0, new Position(selectToLineNumber, selectToColumn), 0));\n }\n // Continuing line selection\n var enteringLineNumber = cursor.modelState.selectionStart.getStartPosition().lineNumber;\n if (position.lineNumber < enteringLineNumber) {\n return CursorState.fromViewState(cursor.viewState.move(cursor.modelState.hasSelection(), viewPosition.lineNumber, 1, 0));\n }\n else if (position.lineNumber > enteringLineNumber) {\n var lineCount = context.viewModel.getLineCount();\n var selectToViewLineNumber = viewPosition.lineNumber + 1;\n var selectToViewColumn = 1;\n if (selectToViewLineNumber > lineCount) {\n selectToViewLineNumber = lineCount;\n selectToViewColumn = context.viewModel.getLineMaxColumn(selectToViewLineNumber);\n }\n return CursorState.fromViewState(cursor.viewState.move(cursor.modelState.hasSelection(), selectToViewLineNumber, selectToViewColumn, 0));\n }\n else {\n var endPositionOfSelectionStart = cursor.modelState.selectionStart.getEndPosition();\n return CursorState.fromModelState(cursor.modelState.move(cursor.modelState.hasSelection(), endPositionOfSelectionStart.lineNumber, endPositionOfSelectionStart.column, 0));\n }\n };\n CursorMoveCommands.word = function (context, cursor, inSelectionMode, _position) {\n var position = context.model.validatePosition(_position);\n return CursorState.fromModelState(WordOperations.word(context.config, context.model, cursor.modelState, inSelectionMode, position));\n };\n CursorMoveCommands.cancelSelection = function (context, cursor) {\n if (!cursor.modelState.hasSelection()) {\n return new CursorState(cursor.modelState, cursor.viewState);\n }\n var lineNumber = cursor.viewState.position.lineNumber;\n var column = cursor.viewState.position.column;\n return CursorState.fromViewState(new SingleCursorState(new Range(lineNumber, column, lineNumber, column), 0, new Position(lineNumber, column), 0));\n };\n CursorMoveCommands.moveTo = function (context, cursor, inSelectionMode, _position, _viewPosition) {\n var position = context.model.validatePosition(_position);\n var viewPosition = (_viewPosition\n ? context.validateViewPosition(new Position(_viewPosition.lineNumber, _viewPosition.column), position)\n : context.convertModelPositionToViewPosition(position));\n return CursorState.fromViewState(cursor.viewState.move(inSelectionMode, viewPosition.lineNumber, viewPosition.column, 0));\n };\n CursorMoveCommands.move = function (context, cursors, args) {\n var inSelectionMode = args.select;\n var value = args.value;\n switch (args.direction) {\n case 0 /* Left */: {\n if (args.unit === 4 /* HalfLine */) {\n // Move left by half the current line length\n return this._moveHalfLineLeft(context, cursors, inSelectionMode);\n }\n else {\n // Move left by `moveParams.value` columns\n return this._moveLeft(context, cursors, inSelectionMode, value);\n }\n }\n case 1 /* Right */: {\n if (args.unit === 4 /* HalfLine */) {\n // Move right by half the current line length\n return this._moveHalfLineRight(context, cursors, inSelectionMode);\n }\n else {\n // Move right by `moveParams.value` columns\n return this._moveRight(context, cursors, inSelectionMode, value);\n }\n }\n case 2 /* Up */: {\n if (args.unit === 2 /* WrappedLine */) {\n // Move up by view lines\n return this._moveUpByViewLines(context, cursors, inSelectionMode, value);\n }\n else {\n // Move up by model lines\n return this._moveUpByModelLines(context, cursors, inSelectionMode, value);\n }\n }\n case 3 /* Down */: {\n if (args.unit === 2 /* WrappedLine */) {\n // Move down by view lines\n return this._moveDownByViewLines(context, cursors, inSelectionMode, value);\n }\n else {\n // Move down by model lines\n return this._moveDownByModelLines(context, cursors, inSelectionMode, value);\n }\n }\n case 4 /* WrappedLineStart */: {\n // Move to the beginning of the current view line\n return this._moveToViewMinColumn(context, cursors, inSelectionMode);\n }\n case 5 /* WrappedLineFirstNonWhitespaceCharacter */: {\n // Move to the first non-whitespace column of the current view line\n return this._moveToViewFirstNonWhitespaceColumn(context, cursors, inSelectionMode);\n }\n case 6 /* WrappedLineColumnCenter */: {\n // Move to the \"center\" of the current view line\n return this._moveToViewCenterColumn(context, cursors, inSelectionMode);\n }\n case 7 /* WrappedLineEnd */: {\n // Move to the end of the current view line\n return this._moveToViewMaxColumn(context, cursors, inSelectionMode);\n }\n case 8 /* WrappedLineLastNonWhitespaceCharacter */: {\n // Move to the last non-whitespace column of the current view line\n return this._moveToViewLastNonWhitespaceColumn(context, cursors, inSelectionMode);\n }\n case 9 /* ViewPortTop */: {\n // Move to the nth line start in the viewport (from the top)\n var cursor = cursors[0];\n var visibleModelRange = context.getCompletelyVisibleModelRange();\n var modelLineNumber = this._firstLineNumberInRange(context.model, visibleModelRange, value);\n var modelColumn = context.model.getLineFirstNonWhitespaceColumn(modelLineNumber);\n return [this._moveToModelPosition(context, cursor, inSelectionMode, modelLineNumber, modelColumn)];\n }\n case 11 /* ViewPortBottom */: {\n // Move to the nth line start in the viewport (from the bottom)\n var cursor = cursors[0];\n var visibleModelRange = context.getCompletelyVisibleModelRange();\n var modelLineNumber = this._lastLineNumberInRange(context.model, visibleModelRange, value);\n var modelColumn = context.model.getLineFirstNonWhitespaceColumn(modelLineNumber);\n return [this._moveToModelPosition(context, cursor, inSelectionMode, modelLineNumber, modelColumn)];\n }\n case 10 /* ViewPortCenter */: {\n // Move to the line start in the viewport center\n var cursor = cursors[0];\n var visibleModelRange = context.getCompletelyVisibleModelRange();\n var modelLineNumber = Math.round((visibleModelRange.startLineNumber + visibleModelRange.endLineNumber) / 2);\n var modelColumn = context.model.getLineFirstNonWhitespaceColumn(modelLineNumber);\n return [this._moveToModelPosition(context, cursor, inSelectionMode, modelLineNumber, modelColumn)];\n }\n case 12 /* ViewPortIfOutside */: {\n // Move to a position inside the viewport\n var visibleViewRange = context.getCompletelyVisibleViewRange();\n var result = [];\n for (var i = 0, len = cursors.length; i < len; i++) {\n var cursor = cursors[i];\n result[i] = this.findPositionInViewportIfOutside(context, cursor, visibleViewRange, inSelectionMode);\n }\n return result;\n }\n }\n return null;\n };\n CursorMoveCommands.findPositionInViewportIfOutside = function (context, cursor, visibleViewRange, inSelectionMode) {\n var viewLineNumber = cursor.viewState.position.lineNumber;\n if (visibleViewRange.startLineNumber <= viewLineNumber && viewLineNumber <= visibleViewRange.endLineNumber - 1) {\n // Nothing to do, cursor is in viewport\n return new CursorState(cursor.modelState, cursor.viewState);\n }\n else {\n if (viewLineNumber > visibleViewRange.endLineNumber - 1) {\n viewLineNumber = visibleViewRange.endLineNumber - 1;\n }\n if (viewLineNumber < visibleViewRange.startLineNumber) {\n viewLineNumber = visibleViewRange.startLineNumber;\n }\n var viewColumn = context.viewModel.getLineFirstNonWhitespaceColumn(viewLineNumber);\n return this._moveToViewPosition(context, cursor, inSelectionMode, viewLineNumber, viewColumn);\n }\n };\n /**\n * Find the nth line start included in the range (from the start).\n */\n CursorMoveCommands._firstLineNumberInRange = function (model, range, count) {\n var startLineNumber = range.startLineNumber;\n if (range.startColumn !== model.getLineMinColumn(startLineNumber)) {\n // Move on to the second line if the first line start is not included in the range\n startLineNumber++;\n }\n return Math.min(range.endLineNumber, startLineNumber + count - 1);\n };\n /**\n * Find the nth line start included in the range (from the end).\n */\n CursorMoveCommands._lastLineNumberInRange = function (model, range, count) {\n var startLineNumber = range.startLineNumber;\n if (range.startColumn !== model.getLineMinColumn(startLineNumber)) {\n // Move on to the second line if the first line start is not included in the range\n startLineNumber++;\n }\n return Math.max(startLineNumber, range.endLineNumber - count + 1);\n };\n CursorMoveCommands._moveLeft = function (context, cursors, inSelectionMode, noOfColumns) {\n var result = [];\n for (var i = 0, len = cursors.length; i < len; i++) {\n var cursor = cursors[i];\n var newViewState = MoveOperations.moveLeft(context.config, context.viewModel, cursor.viewState, inSelectionMode, noOfColumns);\n if (noOfColumns === 1 && newViewState.position.lineNumber !== cursor.viewState.position.lineNumber) {\n // moved over to the previous view line\n var newViewModelPosition = context.viewModel.coordinatesConverter.convertViewPositionToModelPosition(newViewState.position);\n if (newViewModelPosition.lineNumber === cursor.modelState.position.lineNumber) {\n // stayed on the same model line => pass wrapping point where 2 view positions map to a single model position\n newViewState = MoveOperations.moveLeft(context.config, context.viewModel, newViewState, inSelectionMode, 1);\n }\n }\n result[i] = CursorState.fromViewState(newViewState);\n }\n return result;\n };\n CursorMoveCommands._moveHalfLineLeft = function (context, cursors, inSelectionMode) {\n var result = [];\n for (var i = 0, len = cursors.length; i < len; i++) {\n var cursor = cursors[i];\n var viewLineNumber = cursor.viewState.position.lineNumber;\n var halfLine = Math.round(context.viewModel.getLineContent(viewLineNumber).length / 2);\n result[i] = CursorState.fromViewState(MoveOperations.moveLeft(context.config, context.viewModel, cursor.viewState, inSelectionMode, halfLine));\n }\n return result;\n };\n CursorMoveCommands._moveRight = function (context, cursors, inSelectionMode, noOfColumns) {\n var result = [];\n for (var i = 0, len = cursors.length; i < len; i++) {\n var cursor = cursors[i];\n var newViewState = MoveOperations.moveRight(context.config, context.viewModel, cursor.viewState, inSelectionMode, noOfColumns);\n if (noOfColumns === 1 && newViewState.position.lineNumber !== cursor.viewState.position.lineNumber) {\n // moved over to the next view line\n var newViewModelPosition = context.viewModel.coordinatesConverter.convertViewPositionToModelPosition(newViewState.position);\n if (newViewModelPosition.lineNumber === cursor.modelState.position.lineNumber) {\n // stayed on the same model line => pass wrapping point where 2 view positions map to a single model position\n newViewState = MoveOperations.moveRight(context.config, context.viewModel, newViewState, inSelectionMode, 1);\n }\n }\n result[i] = CursorState.fromViewState(newViewState);\n }\n return result;\n };\n CursorMoveCommands._moveHalfLineRight = function (context, cursors, inSelectionMode) {\n var result = [];\n for (var i = 0, len = cursors.length; i < len; i++) {\n var cursor = cursors[i];\n var viewLineNumber = cursor.viewState.position.lineNumber;\n var halfLine = Math.round(context.viewModel.getLineContent(viewLineNumber).length / 2);\n result[i] = CursorState.fromViewState(MoveOperations.moveRight(context.config, context.viewModel, cursor.viewState, inSelectionMode, halfLine));\n }\n return result;\n };\n CursorMoveCommands._moveDownByViewLines = function (context, cursors, inSelectionMode, linesCount) {\n var result = [];\n for (var i = 0, len = cursors.length; i < len; i++) {\n var cursor = cursors[i];\n result[i] = CursorState.fromViewState(MoveOperations.moveDown(context.config, context.viewModel, cursor.viewState, inSelectionMode, linesCount));\n }\n return result;\n };\n CursorMoveCommands._moveDownByModelLines = function (context, cursors, inSelectionMode, linesCount) {\n var result = [];\n for (var i = 0, len = cursors.length; i < len; i++) {\n var cursor = cursors[i];\n result[i] = CursorState.fromModelState(MoveOperations.moveDown(context.config, context.model, cursor.modelState, inSelectionMode, linesCount));\n }\n return result;\n };\n CursorMoveCommands._moveUpByViewLines = function (context, cursors, inSelectionMode, linesCount) {\n var result = [];\n for (var i = 0, len = cursors.length; i < len; i++) {\n var cursor = cursors[i];\n result[i] = CursorState.fromViewState(MoveOperations.moveUp(context.config, context.viewModel, cursor.viewState, inSelectionMode, linesCount));\n }\n return result;\n };\n CursorMoveCommands._moveUpByModelLines = function (context, cursors, inSelectionMode, linesCount) {\n var result = [];\n for (var i = 0, len = cursors.length; i < len; i++) {\n var cursor = cursors[i];\n result[i] = CursorState.fromModelState(MoveOperations.moveUp(context.config, context.model, cursor.modelState, inSelectionMode, linesCount));\n }\n return result;\n };\n CursorMoveCommands._moveToViewPosition = function (context, cursor, inSelectionMode, toViewLineNumber, toViewColumn) {\n return CursorState.fromViewState(cursor.viewState.move(inSelectionMode, toViewLineNumber, toViewColumn, 0));\n };\n CursorMoveCommands._moveToModelPosition = function (context, cursor, inSelectionMode, toModelLineNumber, toModelColumn) {\n return CursorState.fromModelState(cursor.modelState.move(inSelectionMode, toModelLineNumber, toModelColumn, 0));\n };\n CursorMoveCommands._moveToViewMinColumn = function (context, cursors, inSelectionMode) {\n var result = [];\n for (var i = 0, len = cursors.length; i < len; i++) {\n var cursor = cursors[i];\n var viewLineNumber = cursor.viewState.position.lineNumber;\n var viewColumn = context.viewModel.getLineMinColumn(viewLineNumber);\n result[i] = this._moveToViewPosition(context, cursor, inSelectionMode, viewLineNumber, viewColumn);\n }\n return result;\n };\n CursorMoveCommands._moveToViewFirstNonWhitespaceColumn = function (context, cursors, inSelectionMode) {\n var result = [];\n for (var i = 0, len = cursors.length; i < len; i++) {\n var cursor = cursors[i];\n var viewLineNumber = cursor.viewState.position.lineNumber;\n var viewColumn = context.viewModel.getLineFirstNonWhitespaceColumn(viewLineNumber);\n result[i] = this._moveToViewPosition(context, cursor, inSelectionMode, viewLineNumber, viewColumn);\n }\n return result;\n };\n CursorMoveCommands._moveToViewCenterColumn = function (context, cursors, inSelectionMode) {\n var result = [];\n for (var i = 0, len = cursors.length; i < len; i++) {\n var cursor = cursors[i];\n var viewLineNumber = cursor.viewState.position.lineNumber;\n var viewColumn = Math.round((context.viewModel.getLineMaxColumn(viewLineNumber) + context.viewModel.getLineMinColumn(viewLineNumber)) / 2);\n result[i] = this._moveToViewPosition(context, cursor, inSelectionMode, viewLineNumber, viewColumn);\n }\n return result;\n };\n CursorMoveCommands._moveToViewMaxColumn = function (context, cursors, inSelectionMode) {\n var result = [];\n for (var i = 0, len = cursors.length; i < len; i++) {\n var cursor = cursors[i];\n var viewLineNumber = cursor.viewState.position.lineNumber;\n var viewColumn = context.viewModel.getLineMaxColumn(viewLineNumber);\n result[i] = this._moveToViewPosition(context, cursor, inSelectionMode, viewLineNumber, viewColumn);\n }\n return result;\n };\n CursorMoveCommands._moveToViewLastNonWhitespaceColumn = function (context, cursors, inSelectionMode) {\n var result = [];\n for (var i = 0, len = cursors.length; i < len; i++) {\n var cursor = cursors[i];\n var viewLineNumber = cursor.viewState.position.lineNumber;\n var viewColumn = context.viewModel.getLineLastNonWhitespaceColumn(viewLineNumber);\n result[i] = this._moveToViewPosition(context, cursor, inSelectionMode, viewLineNumber, viewColumn);\n }\n return result;\n };\n return CursorMoveCommands;\n}());\nexport { CursorMoveCommands };\nexport var CursorMove;\n(function (CursorMove) {\n var isCursorMoveArgs = function (arg) {\n if (!types.isObject(arg)) {\n return false;\n }\n var cursorMoveArg = arg;\n if (!types.isString(cursorMoveArg.to)) {\n return false;\n }\n if (!types.isUndefined(cursorMoveArg.select) && !types.isBoolean(cursorMoveArg.select)) {\n return false;\n }\n if (!types.isUndefined(cursorMoveArg.by) && !types.isString(cursorMoveArg.by)) {\n return false;\n }\n if (!types.isUndefined(cursorMoveArg.value) && !types.isNumber(cursorMoveArg.value)) {\n return false;\n }\n return true;\n };\n CursorMove.description = {\n description: 'Move cursor to a logical position in the view',\n args: [\n {\n name: 'Cursor move argument object',\n description: \"Property-value pairs that can be passed through this argument:\\n\\t\\t\\t\\t\\t* 'to': A mandatory logical position value providing where to move the cursor.\\n\\t\\t\\t\\t\\t\\t```\\n\\t\\t\\t\\t\\t\\t'left', 'right', 'up', 'down'\\n\\t\\t\\t\\t\\t\\t'wrappedLineStart', 'wrappedLineEnd', 'wrappedLineColumnCenter'\\n\\t\\t\\t\\t\\t\\t'wrappedLineFirstNonWhitespaceCharacter', 'wrappedLineLastNonWhitespaceCharacter'\\n\\t\\t\\t\\t\\t\\t'viewPortTop', 'viewPortCenter', 'viewPortBottom', 'viewPortIfOutside'\\n\\t\\t\\t\\t\\t\\t```\\n\\t\\t\\t\\t\\t* 'by': Unit to move. Default is computed based on 'to' value.\\n\\t\\t\\t\\t\\t\\t```\\n\\t\\t\\t\\t\\t\\t'line', 'wrappedLine', 'character', 'halfLine'\\n\\t\\t\\t\\t\\t\\t```\\n\\t\\t\\t\\t\\t* 'value': Number of units to move. Default is '1'.\\n\\t\\t\\t\\t\\t* 'select': If 'true' makes the selection. Default is 'false'.\\n\\t\\t\\t\\t\",\n constraint: isCursorMoveArgs,\n schema: {\n 'type': 'object',\n 'required': ['to'],\n 'properties': {\n 'to': {\n 'type': 'string',\n 'enum': ['left', 'right', 'up', 'down', 'wrappedLineStart', 'wrappedLineEnd', 'wrappedLineColumnCenter', 'wrappedLineFirstNonWhitespaceCharacter', 'wrappedLineLastNonWhitespaceCharacter', 'viewPortTop', 'viewPortCenter', 'viewPortBottom', 'viewPortIfOutside']\n },\n 'by': {\n 'type': 'string',\n 'enum': ['line', 'wrappedLine', 'character', 'halfLine']\n },\n 'value': {\n 'type': 'number',\n 'default': 1\n },\n 'select': {\n 'type': 'boolean',\n 'default': false\n }\n }\n }\n }\n ]\n };\n /**\n * Positions in the view for cursor move command.\n */\n CursorMove.RawDirection = {\n Left: 'left',\n Right: 'right',\n Up: 'up',\n Down: 'down',\n WrappedLineStart: 'wrappedLineStart',\n WrappedLineFirstNonWhitespaceCharacter: 'wrappedLineFirstNonWhitespaceCharacter',\n WrappedLineColumnCenter: 'wrappedLineColumnCenter',\n WrappedLineEnd: 'wrappedLineEnd',\n WrappedLineLastNonWhitespaceCharacter: 'wrappedLineLastNonWhitespaceCharacter',\n ViewPortTop: 'viewPortTop',\n ViewPortCenter: 'viewPortCenter',\n ViewPortBottom: 'viewPortBottom',\n ViewPortIfOutside: 'viewPortIfOutside'\n };\n /**\n * Units for Cursor move 'by' argument\n */\n CursorMove.RawUnit = {\n Line: 'line',\n WrappedLine: 'wrappedLine',\n Character: 'character',\n HalfLine: 'halfLine'\n };\n function parse(args) {\n if (!args.to) {\n // illegal arguments\n return null;\n }\n var direction;\n switch (args.to) {\n case CursorMove.RawDirection.Left:\n direction = 0 /* Left */;\n break;\n case CursorMove.RawDirection.Right:\n direction = 1 /* Right */;\n break;\n case CursorMove.RawDirection.Up:\n direction = 2 /* Up */;\n break;\n case CursorMove.RawDirection.Down:\n direction = 3 /* Down */;\n break;\n case CursorMove.RawDirection.WrappedLineStart:\n direction = 4 /* WrappedLineStart */;\n break;\n case CursorMove.RawDirection.WrappedLineFirstNonWhitespaceCharacter:\n direction = 5 /* WrappedLineFirstNonWhitespaceCharacter */;\n break;\n case CursorMove.RawDirection.WrappedLineColumnCenter:\n direction = 6 /* WrappedLineColumnCenter */;\n break;\n case CursorMove.RawDirection.WrappedLineEnd:\n direction = 7 /* WrappedLineEnd */;\n break;\n case CursorMove.RawDirection.WrappedLineLastNonWhitespaceCharacter:\n direction = 8 /* WrappedLineLastNonWhitespaceCharacter */;\n break;\n case CursorMove.RawDirection.ViewPortTop:\n direction = 9 /* ViewPortTop */;\n break;\n case CursorMove.RawDirection.ViewPortBottom:\n direction = 11 /* ViewPortBottom */;\n break;\n case CursorMove.RawDirection.ViewPortCenter:\n direction = 10 /* ViewPortCenter */;\n break;\n case CursorMove.RawDirection.ViewPortIfOutside:\n direction = 12 /* ViewPortIfOutside */;\n break;\n default:\n // illegal arguments\n return null;\n }\n var unit = 0 /* None */;\n switch (args.by) {\n case CursorMove.RawUnit.Line:\n unit = 1 /* Line */;\n break;\n case CursorMove.RawUnit.WrappedLine:\n unit = 2 /* WrappedLine */;\n break;\n case CursorMove.RawUnit.Character:\n unit = 3 /* Character */;\n break;\n case CursorMove.RawUnit.HalfLine:\n unit = 4 /* HalfLine */;\n break;\n }\n return {\n direction: direction,\n unit: unit,\n select: (!!args.select),\n value: (args.value || 1)\n };\n }\n CursorMove.parse = parse;\n})(CursorMove || (CursorMove = {}));\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport * as strings from '../../../base/common/strings.js';\nimport { CursorColumns } from '../controller/cursorCommon.js';\nimport { Range } from '../core/range.js';\nimport { Selection } from '../core/selection.js';\nimport { LanguageConfigurationRegistry } from '../modes/languageConfigurationRegistry.js';\nvar repeatCache = Object.create(null);\nexport function cachedStringRepeat(str, count) {\n if (!repeatCache[str]) {\n repeatCache[str] = ['', str];\n }\n var cache = repeatCache[str];\n for (var i = cache.length; i <= count; i++) {\n cache[i] = cache[i - 1] + str;\n }\n return cache[count];\n}\nvar ShiftCommand = /** @class */ (function () {\n function ShiftCommand(range, opts) {\n this._opts = opts;\n this._selection = range;\n this._useLastEditRangeForCursorEndPosition = false;\n this._selectionStartColumnStaysPut = false;\n }\n ShiftCommand.unshiftIndent = function (line, column, tabSize, indentSize, insertSpaces) {\n // Determine the visible column where the content starts\n var contentStartVisibleColumn = CursorColumns.visibleColumnFromColumn(line, column, tabSize);\n if (insertSpaces) {\n var indent = cachedStringRepeat(' ', indentSize);\n var desiredTabStop = CursorColumns.prevIndentTabStop(contentStartVisibleColumn, indentSize);\n var indentCount = desiredTabStop / indentSize; // will be an integer\n return cachedStringRepeat(indent, indentCount);\n }\n else {\n var indent = '\\t';\n var desiredTabStop = CursorColumns.prevRenderTabStop(contentStartVisibleColumn, tabSize);\n var indentCount = desiredTabStop / tabSize; // will be an integer\n return cachedStringRepeat(indent, indentCount);\n }\n };\n ShiftCommand.shiftIndent = function (line, column, tabSize, indentSize, insertSpaces) {\n // Determine the visible column where the content starts\n var contentStartVisibleColumn = CursorColumns.visibleColumnFromColumn(line, column, tabSize);\n if (insertSpaces) {\n var indent = cachedStringRepeat(' ', indentSize);\n var desiredTabStop = CursorColumns.nextIndentTabStop(contentStartVisibleColumn, indentSize);\n var indentCount = desiredTabStop / indentSize; // will be an integer\n return cachedStringRepeat(indent, indentCount);\n }\n else {\n var indent = '\\t';\n var desiredTabStop = CursorColumns.nextRenderTabStop(contentStartVisibleColumn, tabSize);\n var indentCount = desiredTabStop / tabSize; // will be an integer\n return cachedStringRepeat(indent, indentCount);\n }\n };\n ShiftCommand.prototype._addEditOperation = function (builder, range, text) {\n if (this._useLastEditRangeForCursorEndPosition) {\n builder.addTrackedEditOperation(range, text);\n }\n else {\n builder.addEditOperation(range, text);\n }\n };\n ShiftCommand.prototype.getEditOperations = function (model, builder) {\n var startLine = this._selection.startLineNumber;\n var endLine = this._selection.endLineNumber;\n if (this._selection.endColumn === 1 && startLine !== endLine) {\n endLine = endLine - 1;\n }\n var _a = this._opts, tabSize = _a.tabSize, indentSize = _a.indentSize, insertSpaces = _a.insertSpaces;\n var shouldIndentEmptyLines = (startLine === endLine);\n // if indenting or outdenting on a whitespace only line\n if (this._selection.isEmpty()) {\n if (/^\\s*$/.test(model.getLineContent(startLine))) {\n this._useLastEditRangeForCursorEndPosition = true;\n }\n }\n if (this._opts.useTabStops) {\n // keep track of previous line's \"miss-alignment\"\n var previousLineExtraSpaces = 0, extraSpaces = 0;\n for (var lineNumber = startLine; lineNumber <= endLine; lineNumber++, previousLineExtraSpaces = extraSpaces) {\n extraSpaces = 0;\n var lineText = model.getLineContent(lineNumber);\n var indentationEndIndex = strings.firstNonWhitespaceIndex(lineText);\n if (this._opts.isUnshift && (lineText.length === 0 || indentationEndIndex === 0)) {\n // empty line or line with no leading whitespace => nothing to do\n continue;\n }\n if (!shouldIndentEmptyLines && !this._opts.isUnshift && lineText.length === 0) {\n // do not indent empty lines => nothing to do\n continue;\n }\n if (indentationEndIndex === -1) {\n // the entire line is whitespace\n indentationEndIndex = lineText.length;\n }\n if (lineNumber > 1) {\n var contentStartVisibleColumn = CursorColumns.visibleColumnFromColumn(lineText, indentationEndIndex + 1, tabSize);\n if (contentStartVisibleColumn % indentSize !== 0) {\n // The current line is \"miss-aligned\", so let's see if this is expected...\n // This can only happen when it has trailing commas in the indent\n if (model.isCheapToTokenize(lineNumber - 1)) {\n var enterAction = LanguageConfigurationRegistry.getRawEnterActionAtPosition(model, lineNumber - 1, model.getLineMaxColumn(lineNumber - 1));\n if (enterAction) {\n extraSpaces = previousLineExtraSpaces;\n if (enterAction.appendText) {\n for (var j = 0, lenJ = enterAction.appendText.length; j < lenJ && extraSpaces < indentSize; j++) {\n if (enterAction.appendText.charCodeAt(j) === 32 /* Space */) {\n extraSpaces++;\n }\n else {\n break;\n }\n }\n }\n if (enterAction.removeText) {\n extraSpaces = Math.max(0, extraSpaces - enterAction.removeText);\n }\n // Act as if `prefixSpaces` is not part of the indentation\n for (var j = 0; j < extraSpaces; j++) {\n if (indentationEndIndex === 0 || lineText.charCodeAt(indentationEndIndex - 1) !== 32 /* Space */) {\n break;\n }\n indentationEndIndex--;\n }\n }\n }\n }\n }\n if (this._opts.isUnshift && indentationEndIndex === 0) {\n // line with no leading whitespace => nothing to do\n continue;\n }\n var desiredIndent = void 0;\n if (this._opts.isUnshift) {\n desiredIndent = ShiftCommand.unshiftIndent(lineText, indentationEndIndex + 1, tabSize, indentSize, insertSpaces);\n }\n else {\n desiredIndent = ShiftCommand.shiftIndent(lineText, indentationEndIndex + 1, tabSize, indentSize, insertSpaces);\n }\n this._addEditOperation(builder, new Range(lineNumber, 1, lineNumber, indentationEndIndex + 1), desiredIndent);\n if (lineNumber === startLine) {\n // Force the startColumn to stay put because we're inserting after it\n this._selectionStartColumnStaysPut = (this._selection.startColumn <= indentationEndIndex + 1);\n }\n }\n }\n else {\n var oneIndent = (insertSpaces ? cachedStringRepeat(' ', indentSize) : '\\t');\n for (var lineNumber = startLine; lineNumber <= endLine; lineNumber++) {\n var lineText = model.getLineContent(lineNumber);\n var indentationEndIndex = strings.firstNonWhitespaceIndex(lineText);\n if (this._opts.isUnshift && (lineText.length === 0 || indentationEndIndex === 0)) {\n // empty line or line with no leading whitespace => nothing to do\n continue;\n }\n if (!shouldIndentEmptyLines && !this._opts.isUnshift && lineText.length === 0) {\n // do not indent empty lines => nothing to do\n continue;\n }\n if (indentationEndIndex === -1) {\n // the entire line is whitespace\n indentationEndIndex = lineText.length;\n }\n if (this._opts.isUnshift && indentationEndIndex === 0) {\n // line with no leading whitespace => nothing to do\n continue;\n }\n if (this._opts.isUnshift) {\n indentationEndIndex = Math.min(indentationEndIndex, indentSize);\n for (var i = 0; i < indentationEndIndex; i++) {\n var chr = lineText.charCodeAt(i);\n if (chr === 9 /* Tab */) {\n indentationEndIndex = i + 1;\n break;\n }\n }\n this._addEditOperation(builder, new Range(lineNumber, 1, lineNumber, indentationEndIndex + 1), '');\n }\n else {\n this._addEditOperation(builder, new Range(lineNumber, 1, lineNumber, 1), oneIndent);\n if (lineNumber === startLine) {\n // Force the startColumn to stay put because we're inserting after it\n this._selectionStartColumnStaysPut = (this._selection.startColumn === 1);\n }\n }\n }\n }\n this._selectionId = builder.trackSelection(this._selection);\n };\n ShiftCommand.prototype.computeCursorState = function (model, helper) {\n if (this._useLastEditRangeForCursorEndPosition) {\n var lastOp = helper.getInverseEditOperations()[0];\n return new Selection(lastOp.range.endLineNumber, lastOp.range.endColumn, lastOp.range.endLineNumber, lastOp.range.endColumn);\n }\n var result = helper.getTrackedSelection(this._selectionId);\n if (this._selectionStartColumnStaysPut) {\n // The selection start should not move\n var initialStartColumn = this._selection.startColumn;\n var resultStartColumn = result.startColumn;\n if (resultStartColumn <= initialStartColumn) {\n return result;\n }\n if (result.getDirection() === 0 /* LTR */) {\n return new Selection(result.startLineNumber, initialStartColumn, result.endLineNumber, result.endColumn);\n }\n return new Selection(result.endLineNumber, result.endColumn, result.startLineNumber, initialStartColumn);\n }\n return result;\n };\n return ShiftCommand;\n}());\nexport { ShiftCommand };\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport { RawContextKey } from '../../platform/contextkey/common/contextkey.js';\nexport var EditorContextKeys;\n(function (EditorContextKeys) {\n /**\n * A context key that is set when the editor's text has focus (cursor is blinking).\n */\n EditorContextKeys.editorTextFocus = new RawContextKey('editorTextFocus', false);\n /**\n * A context key that is set when the editor's text or an editor's widget has focus.\n */\n EditorContextKeys.focus = new RawContextKey('editorFocus', false);\n /**\n * A context key that is set when any editor input has focus (regular editor, repl input...).\n */\n EditorContextKeys.textInputFocus = new RawContextKey('textInputFocus', false);\n EditorContextKeys.readOnly = new RawContextKey('editorReadonly', false);\n EditorContextKeys.writable = EditorContextKeys.readOnly.toNegated();\n EditorContextKeys.hasNonEmptySelection = new RawContextKey('editorHasSelection', false);\n EditorContextKeys.hasOnlyEmptySelection = EditorContextKeys.hasNonEmptySelection.toNegated();\n EditorContextKeys.hasMultipleSelections = new RawContextKey('editorHasMultipleSelections', false);\n EditorContextKeys.hasSingleSelection = EditorContextKeys.hasMultipleSelections.toNegated();\n EditorContextKeys.tabMovesFocus = new RawContextKey('editorTabMovesFocus', false);\n EditorContextKeys.tabDoesNotMoveFocus = EditorContextKeys.tabMovesFocus.toNegated();\n EditorContextKeys.isInEmbeddedEditor = new RawContextKey('isInEmbeddedEditor', false);\n EditorContextKeys.canUndo = new RawContextKey('canUndo', false);\n EditorContextKeys.canRedo = new RawContextKey('canRedo', false);\n // -- mode context keys\n EditorContextKeys.languageId = new RawContextKey('editorLangId', '');\n EditorContextKeys.hasCompletionItemProvider = new RawContextKey('editorHasCompletionItemProvider', false);\n EditorContextKeys.hasCodeActionsProvider = new RawContextKey('editorHasCodeActionsProvider', false);\n EditorContextKeys.hasCodeLensProvider = new RawContextKey('editorHasCodeLensProvider', false);\n EditorContextKeys.hasDefinitionProvider = new RawContextKey('editorHasDefinitionProvider', false);\n EditorContextKeys.hasDeclarationProvider = new RawContextKey('editorHasDeclarationProvider', false);\n EditorContextKeys.hasImplementationProvider = new RawContextKey('editorHasImplementationProvider', false);\n EditorContextKeys.hasTypeDefinitionProvider = new RawContextKey('editorHasTypeDefinitionProvider', false);\n EditorContextKeys.hasHoverProvider = new RawContextKey('editorHasHoverProvider', false);\n EditorContextKeys.hasDocumentHighlightProvider = new RawContextKey('editorHasDocumentHighlightProvider', false);\n EditorContextKeys.hasDocumentSymbolProvider = new RawContextKey('editorHasDocumentSymbolProvider', false);\n EditorContextKeys.hasReferenceProvider = new RawContextKey('editorHasReferenceProvider', false);\n EditorContextKeys.hasRenameProvider = new RawContextKey('editorHasRenameProvider', false);\n EditorContextKeys.hasSignatureHelpProvider = new RawContextKey('editorHasSignatureHelpProvider', false);\n // -- mode context keys: formatting\n EditorContextKeys.hasDocumentFormattingProvider = new RawContextKey('editorHasDocumentFormattingProvider', false);\n EditorContextKeys.hasDocumentSelectionFormattingProvider = new RawContextKey('editorHasDocumentSelectionFormattingProvider', false);\n EditorContextKeys.hasMultipleDocumentFormattingProvider = new RawContextKey('editorHasMultipleDocumentFormattingProvider', false);\n EditorContextKeys.hasMultipleDocumentSelectionFormattingProvider = new RawContextKey('editorHasMultipleDocumentSelectionFormattingProvider', false);\n})(EditorContextKeys || (EditorContextKeys = {}));\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport { Range } from '../core/range.js';\nimport { Selection } from '../core/selection.js';\nvar SurroundSelectionCommand = /** @class */ (function () {\n function SurroundSelectionCommand(range, charBeforeSelection, charAfterSelection) {\n this._range = range;\n this._charBeforeSelection = charBeforeSelection;\n this._charAfterSelection = charAfterSelection;\n }\n SurroundSelectionCommand.prototype.getEditOperations = function (model, builder) {\n builder.addTrackedEditOperation(new Range(this._range.startLineNumber, this._range.startColumn, this._range.startLineNumber, this._range.startColumn), this._charBeforeSelection);\n builder.addTrackedEditOperation(new Range(this._range.endLineNumber, this._range.endColumn, this._range.endLineNumber, this._range.endColumn), this._charAfterSelection);\n };\n SurroundSelectionCommand.prototype.computeCursorState = function (model, helper) {\n var inverseEditOperations = helper.getInverseEditOperations();\n var firstOperationRange = inverseEditOperations[0].range;\n var secondOperationRange = inverseEditOperations[1].range;\n return new Selection(firstOperationRange.endLineNumber, firstOperationRange.endColumn, secondOperationRange.endLineNumber, secondOperationRange.endColumn - this._charAfterSelection.length);\n };\n return SurroundSelectionCommand;\n}());\nexport { SurroundSelectionCommand };\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport { onUnexpectedError } from '../../../base/common/errors.js';\nimport * as strings from '../../../base/common/strings.js';\nimport { ReplaceCommand, ReplaceCommandWithOffsetCursorState, ReplaceCommandWithoutChangingPosition } from '../commands/replaceCommand.js';\nimport { ShiftCommand } from '../commands/shiftCommand.js';\nimport { SurroundSelectionCommand } from '../commands/surroundSelectionCommand.js';\nimport { CursorColumns, EditOperationResult, isQuote } from './cursorCommon.js';\nimport { getMapForWordSeparators } from './wordCharacterClassifier.js';\nimport { Range } from '../core/range.js';\nimport { IndentAction } from '../modes/languageConfiguration.js';\nimport { LanguageConfigurationRegistry } from '../modes/languageConfigurationRegistry.js';\nvar TypeOperations = /** @class */ (function () {\n function TypeOperations() {\n }\n TypeOperations.indent = function (config, model, selections) {\n if (model === null || selections === null) {\n return [];\n }\n var commands = [];\n for (var i = 0, len = selections.length; i < len; i++) {\n commands[i] = new ShiftCommand(selections[i], {\n isUnshift: false,\n tabSize: config.tabSize,\n indentSize: config.indentSize,\n insertSpaces: config.insertSpaces,\n useTabStops: config.useTabStops\n });\n }\n return commands;\n };\n TypeOperations.outdent = function (config, model, selections) {\n var commands = [];\n for (var i = 0, len = selections.length; i < len; i++) {\n commands[i] = new ShiftCommand(selections[i], {\n isUnshift: true,\n tabSize: config.tabSize,\n indentSize: config.indentSize,\n insertSpaces: config.insertSpaces,\n useTabStops: config.useTabStops\n });\n }\n return commands;\n };\n TypeOperations.shiftIndent = function (config, indentation, count) {\n count = count || 1;\n return ShiftCommand.shiftIndent(indentation, indentation.length + count, config.tabSize, config.indentSize, config.insertSpaces);\n };\n TypeOperations.unshiftIndent = function (config, indentation, count) {\n count = count || 1;\n return ShiftCommand.unshiftIndent(indentation, indentation.length + count, config.tabSize, config.indentSize, config.insertSpaces);\n };\n TypeOperations._distributedPaste = function (config, model, selections, text) {\n var commands = [];\n for (var i = 0, len = selections.length; i < len; i++) {\n commands[i] = new ReplaceCommand(selections[i], text[i]);\n }\n return new EditOperationResult(0 /* Other */, commands, {\n shouldPushStackElementBefore: true,\n shouldPushStackElementAfter: true\n });\n };\n TypeOperations._simplePaste = function (config, model, selections, text, pasteOnNewLine) {\n var commands = [];\n for (var i = 0, len = selections.length; i < len; i++) {\n var selection = selections[i];\n var position = selection.getPosition();\n if (pasteOnNewLine && text.indexOf('\\n') !== text.length - 1) {\n pasteOnNewLine = false;\n }\n if (pasteOnNewLine && selection.startLineNumber !== selection.endLineNumber) {\n pasteOnNewLine = false;\n }\n if (pasteOnNewLine && selection.startColumn === model.getLineMinColumn(selection.startLineNumber) && selection.endColumn === model.getLineMaxColumn(selection.startLineNumber)) {\n pasteOnNewLine = false;\n }\n if (pasteOnNewLine) {\n // Paste entire line at the beginning of line\n var typeSelection = new Range(position.lineNumber, 1, position.lineNumber, 1);\n commands[i] = new ReplaceCommand(typeSelection, text);\n }\n else {\n commands[i] = new ReplaceCommand(selection, text);\n }\n }\n return new EditOperationResult(0 /* Other */, commands, {\n shouldPushStackElementBefore: true,\n shouldPushStackElementAfter: true\n });\n };\n TypeOperations._distributePasteToCursors = function (selections, text, pasteOnNewLine, multicursorText) {\n if (pasteOnNewLine) {\n return null;\n }\n if (selections.length === 1) {\n return null;\n }\n if (multicursorText && multicursorText.length === selections.length) {\n return multicursorText;\n }\n // Remove trailing \\n if present\n if (text.charCodeAt(text.length - 1) === 10 /* LineFeed */) {\n text = text.substr(0, text.length - 1);\n }\n var lines = text.split(/\\r\\n|\\r|\\n/);\n if (lines.length === selections.length) {\n return lines;\n }\n return null;\n };\n TypeOperations.paste = function (config, model, selections, text, pasteOnNewLine, multicursorText) {\n var distributedPaste = this._distributePasteToCursors(selections, text, pasteOnNewLine, multicursorText);\n if (distributedPaste) {\n selections = selections.sort(Range.compareRangesUsingStarts);\n return this._distributedPaste(config, model, selections, distributedPaste);\n }\n else {\n return this._simplePaste(config, model, selections, text, pasteOnNewLine);\n }\n };\n TypeOperations._goodIndentForLine = function (config, model, lineNumber) {\n var action = null;\n var indentation = '';\n var expectedIndentAction = config.autoIndent ? LanguageConfigurationRegistry.getInheritIndentForLine(model, lineNumber, false) : null;\n if (expectedIndentAction) {\n action = expectedIndentAction.action;\n indentation = expectedIndentAction.indentation;\n }\n else if (lineNumber > 1) {\n var lastLineNumber = void 0;\n for (lastLineNumber = lineNumber - 1; lastLineNumber >= 1; lastLineNumber--) {\n var lineText = model.getLineContent(lastLineNumber);\n var nonWhitespaceIdx = strings.lastNonWhitespaceIndex(lineText);\n if (nonWhitespaceIdx >= 0) {\n break;\n }\n }\n if (lastLineNumber < 1) {\n // No previous line with content found\n return null;\n }\n var maxColumn = model.getLineMaxColumn(lastLineNumber);\n var expectedEnterAction = LanguageConfigurationRegistry.getEnterAction(model, new Range(lastLineNumber, maxColumn, lastLineNumber, maxColumn));\n if (expectedEnterAction) {\n indentation = expectedEnterAction.indentation;\n action = expectedEnterAction.enterAction;\n if (action) {\n indentation += action.appendText;\n }\n }\n }\n if (action) {\n if (action === IndentAction.Indent) {\n indentation = TypeOperations.shiftIndent(config, indentation);\n }\n if (action === IndentAction.Outdent) {\n indentation = TypeOperations.unshiftIndent(config, indentation);\n }\n indentation = config.normalizeIndentation(indentation);\n }\n if (!indentation) {\n return null;\n }\n return indentation;\n };\n TypeOperations._replaceJumpToNextIndent = function (config, model, selection, insertsAutoWhitespace) {\n var typeText = '';\n var position = selection.getStartPosition();\n if (config.insertSpaces) {\n var visibleColumnFromColumn = CursorColumns.visibleColumnFromColumn2(config, model, position);\n var indentSize = config.indentSize;\n var spacesCnt = indentSize - (visibleColumnFromColumn % indentSize);\n for (var i = 0; i < spacesCnt; i++) {\n typeText += ' ';\n }\n }\n else {\n typeText = '\\t';\n }\n return new ReplaceCommand(selection, typeText, insertsAutoWhitespace);\n };\n TypeOperations.tab = function (config, model, selections) {\n var commands = [];\n for (var i = 0, len = selections.length; i < len; i++) {\n var selection = selections[i];\n if (selection.isEmpty()) {\n var lineText = model.getLineContent(selection.startLineNumber);\n if (/^\\s*$/.test(lineText) && model.isCheapToTokenize(selection.startLineNumber)) {\n var goodIndent = this._goodIndentForLine(config, model, selection.startLineNumber);\n goodIndent = goodIndent || '\\t';\n var possibleTypeText = config.normalizeIndentation(goodIndent);\n if (!strings.startsWith(lineText, possibleTypeText)) {\n commands[i] = new ReplaceCommand(new Range(selection.startLineNumber, 1, selection.startLineNumber, lineText.length + 1), possibleTypeText, true);\n continue;\n }\n }\n commands[i] = this._replaceJumpToNextIndent(config, model, selection, true);\n }\n else {\n if (selection.startLineNumber === selection.endLineNumber) {\n var lineMaxColumn = model.getLineMaxColumn(selection.startLineNumber);\n if (selection.startColumn !== 1 || selection.endColumn !== lineMaxColumn) {\n // This is a single line selection that is not the entire line\n commands[i] = this._replaceJumpToNextIndent(config, model, selection, false);\n continue;\n }\n }\n commands[i] = new ShiftCommand(selection, {\n isUnshift: false,\n tabSize: config.tabSize,\n indentSize: config.indentSize,\n insertSpaces: config.insertSpaces,\n useTabStops: config.useTabStops\n });\n }\n }\n return commands;\n };\n TypeOperations.replacePreviousChar = function (prevEditOperationType, config, model, selections, txt, replaceCharCnt) {\n var commands = [];\n for (var i = 0, len = selections.length; i < len; i++) {\n var selection = selections[i];\n if (!selection.isEmpty()) {\n // looks like https://github.com/Microsoft/vscode/issues/2773\n // where a cursor operation occurred before a canceled composition\n // => ignore composition\n commands[i] = null;\n continue;\n }\n var pos = selection.getPosition();\n var startColumn = Math.max(1, pos.column - replaceCharCnt);\n var range = new Range(pos.lineNumber, startColumn, pos.lineNumber, pos.column);\n commands[i] = new ReplaceCommand(range, txt);\n }\n return new EditOperationResult(1 /* Typing */, commands, {\n shouldPushStackElementBefore: (prevEditOperationType !== 1 /* Typing */),\n shouldPushStackElementAfter: false\n });\n };\n TypeOperations._typeCommand = function (range, text, keepPosition) {\n if (keepPosition) {\n return new ReplaceCommandWithoutChangingPosition(range, text, true);\n }\n else {\n return new ReplaceCommand(range, text, true);\n }\n };\n TypeOperations._enter = function (config, model, keepPosition, range) {\n if (!model.isCheapToTokenize(range.getStartPosition().lineNumber)) {\n var lineText_1 = model.getLineContent(range.startLineNumber);\n var indentation_1 = strings.getLeadingWhitespace(lineText_1).substring(0, range.startColumn - 1);\n return TypeOperations._typeCommand(range, '\\n' + config.normalizeIndentation(indentation_1), keepPosition);\n }\n var r = LanguageConfigurationRegistry.getEnterAction(model, range);\n if (r) {\n var enterAction = r.enterAction;\n var indentation_2 = r.indentation;\n if (enterAction.indentAction === IndentAction.None) {\n // Nothing special\n return TypeOperations._typeCommand(range, '\\n' + config.normalizeIndentation(indentation_2 + enterAction.appendText), keepPosition);\n }\n else if (enterAction.indentAction === IndentAction.Indent) {\n // Indent once\n return TypeOperations._typeCommand(range, '\\n' + config.normalizeIndentation(indentation_2 + enterAction.appendText), keepPosition);\n }\n else if (enterAction.indentAction === IndentAction.IndentOutdent) {\n // Ultra special\n var normalIndent = config.normalizeIndentation(indentation_2);\n var increasedIndent = config.normalizeIndentation(indentation_2 + enterAction.appendText);\n var typeText = '\\n' + increasedIndent + '\\n' + normalIndent;\n if (keepPosition) {\n return new ReplaceCommandWithoutChangingPosition(range, typeText, true);\n }\n else {\n return new ReplaceCommandWithOffsetCursorState(range, typeText, -1, increasedIndent.length - normalIndent.length, true);\n }\n }\n else if (enterAction.indentAction === IndentAction.Outdent) {\n var actualIndentation = TypeOperations.unshiftIndent(config, indentation_2);\n return TypeOperations._typeCommand(range, '\\n' + config.normalizeIndentation(actualIndentation + enterAction.appendText), keepPosition);\n }\n }\n // no enter rules applied, we should check indentation rules then.\n if (!config.autoIndent) {\n // Nothing special\n var lineText_2 = model.getLineContent(range.startLineNumber);\n var indentation_3 = strings.getLeadingWhitespace(lineText_2).substring(0, range.startColumn - 1);\n return TypeOperations._typeCommand(range, '\\n' + config.normalizeIndentation(indentation_3), keepPosition);\n }\n var ir = LanguageConfigurationRegistry.getIndentForEnter(model, range, {\n unshiftIndent: function (indent) {\n return TypeOperations.unshiftIndent(config, indent);\n },\n shiftIndent: function (indent) {\n return TypeOperations.shiftIndent(config, indent);\n },\n normalizeIndentation: function (indent) {\n return config.normalizeIndentation(indent);\n }\n }, config.autoIndent);\n var lineText = model.getLineContent(range.startLineNumber);\n var indentation = strings.getLeadingWhitespace(lineText).substring(0, range.startColumn - 1);\n if (ir) {\n var oldEndViewColumn = CursorColumns.visibleColumnFromColumn2(config, model, range.getEndPosition());\n var oldEndColumn = range.endColumn;\n var beforeText = '\\n';\n if (indentation !== config.normalizeIndentation(ir.beforeEnter)) {\n beforeText = config.normalizeIndentation(ir.beforeEnter) + lineText.substring(indentation.length, range.startColumn - 1) + '\\n';\n range = new Range(range.startLineNumber, 1, range.endLineNumber, range.endColumn);\n }\n var newLineContent = model.getLineContent(range.endLineNumber);\n var firstNonWhitespace = strings.firstNonWhitespaceIndex(newLineContent);\n if (firstNonWhitespace >= 0) {\n range = range.setEndPosition(range.endLineNumber, Math.max(range.endColumn, firstNonWhitespace + 1));\n }\n else {\n range = range.setEndPosition(range.endLineNumber, model.getLineMaxColumn(range.endLineNumber));\n }\n if (keepPosition) {\n return new ReplaceCommandWithoutChangingPosition(range, beforeText + config.normalizeIndentation(ir.afterEnter), true);\n }\n else {\n var offset = 0;\n if (oldEndColumn <= firstNonWhitespace + 1) {\n if (!config.insertSpaces) {\n oldEndViewColumn = Math.ceil(oldEndViewColumn / config.indentSize);\n }\n offset = Math.min(oldEndViewColumn + 1 - config.normalizeIndentation(ir.afterEnter).length - 1, 0);\n }\n return new ReplaceCommandWithOffsetCursorState(range, beforeText + config.normalizeIndentation(ir.afterEnter), 0, offset, true);\n }\n }\n else {\n return TypeOperations._typeCommand(range, '\\n' + config.normalizeIndentation(indentation), keepPosition);\n }\n };\n TypeOperations._isAutoIndentType = function (config, model, selections) {\n if (!config.autoIndent) {\n return false;\n }\n for (var i = 0, len = selections.length; i < len; i++) {\n if (!model.isCheapToTokenize(selections[i].getEndPosition().lineNumber)) {\n return false;\n }\n }\n return true;\n };\n TypeOperations._runAutoIndentType = function (config, model, range, ch) {\n var currentIndentation = LanguageConfigurationRegistry.getIndentationAtPosition(model, range.startLineNumber, range.startColumn);\n var actualIndentation = LanguageConfigurationRegistry.getIndentActionForType(model, range, ch, {\n shiftIndent: function (indentation) {\n return TypeOperations.shiftIndent(config, indentation);\n },\n unshiftIndent: function (indentation) {\n return TypeOperations.unshiftIndent(config, indentation);\n },\n });\n if (actualIndentation === null) {\n return null;\n }\n if (actualIndentation !== config.normalizeIndentation(currentIndentation)) {\n var firstNonWhitespace = model.getLineFirstNonWhitespaceColumn(range.startLineNumber);\n if (firstNonWhitespace === 0) {\n return TypeOperations._typeCommand(new Range(range.startLineNumber, 0, range.endLineNumber, range.endColumn), config.normalizeIndentation(actualIndentation) + ch, false);\n }\n else {\n return TypeOperations._typeCommand(new Range(range.startLineNumber, 0, range.endLineNumber, range.endColumn), config.normalizeIndentation(actualIndentation) +\n model.getLineContent(range.startLineNumber).substring(firstNonWhitespace - 1, range.startColumn - 1) + ch, false);\n }\n }\n return null;\n };\n TypeOperations._isAutoClosingCloseCharType = function (config, model, selections, ch) {\n var autoCloseConfig = isQuote(ch) ? config.autoClosingQuotes : config.autoClosingBrackets;\n if (autoCloseConfig === 'never' || !config.autoClosingPairsClose.hasOwnProperty(ch)) {\n return false;\n }\n var isEqualPair = (ch === config.autoClosingPairsClose[ch]);\n for (var i = 0, len = selections.length; i < len; i++) {\n var selection = selections[i];\n if (!selection.isEmpty()) {\n return false;\n }\n var position = selection.getPosition();\n var lineText = model.getLineContent(position.lineNumber);\n var afterCharacter = lineText.charAt(position.column - 1);\n if (afterCharacter !== ch) {\n return false;\n }\n if (isEqualPair) {\n var lineTextBeforeCursor = lineText.substr(0, position.column - 1);\n var chCntBefore = this._countNeedlesInHaystack(lineTextBeforeCursor, ch);\n if (chCntBefore % 2 === 0) {\n return false;\n }\n }\n }\n return true;\n };\n TypeOperations._countNeedlesInHaystack = function (haystack, needle) {\n var cnt = 0;\n var lastIndex = -1;\n while ((lastIndex = haystack.indexOf(needle, lastIndex + 1)) !== -1) {\n cnt++;\n }\n return cnt;\n };\n TypeOperations._runAutoClosingCloseCharType = function (prevEditOperationType, config, model, selections, ch) {\n var commands = [];\n for (var i = 0, len = selections.length; i < len; i++) {\n var selection = selections[i];\n var position = selection.getPosition();\n var typeSelection = new Range(position.lineNumber, position.column, position.lineNumber, position.column + 1);\n commands[i] = new ReplaceCommand(typeSelection, ch);\n }\n return new EditOperationResult(1 /* Typing */, commands, {\n shouldPushStackElementBefore: (prevEditOperationType !== 1 /* Typing */),\n shouldPushStackElementAfter: false\n });\n };\n TypeOperations._isBeforeClosingBrace = function (config, ch, characterAfter) {\n var thisBraceIsSymmetric = (config.autoClosingPairsOpen[ch] === ch);\n var isBeforeCloseBrace = false;\n for (var otherCloseBrace in config.autoClosingPairsClose) {\n var otherBraceIsSymmetric = (config.autoClosingPairsOpen[otherCloseBrace] === otherCloseBrace);\n if (!thisBraceIsSymmetric && otherBraceIsSymmetric) {\n continue;\n }\n if (characterAfter === otherCloseBrace) {\n isBeforeCloseBrace = true;\n break;\n }\n }\n return isBeforeCloseBrace;\n };\n TypeOperations._isAutoClosingOpenCharType = function (config, model, selections, ch) {\n var chIsQuote = isQuote(ch);\n var autoCloseConfig = chIsQuote ? config.autoClosingQuotes : config.autoClosingBrackets;\n if (autoCloseConfig === 'never' || !config.autoClosingPairsOpen.hasOwnProperty(ch)) {\n return false;\n }\n var shouldAutoCloseBefore = chIsQuote ? config.shouldAutoCloseBefore.quote : config.shouldAutoCloseBefore.bracket;\n for (var i = 0, len = selections.length; i < len; i++) {\n var selection = selections[i];\n if (!selection.isEmpty()) {\n return false;\n }\n var position = selection.getPosition();\n var lineText = model.getLineContent(position.lineNumber);\n // Do not auto-close ' or \" after a word character\n if ((chIsQuote && position.column > 1) && autoCloseConfig !== 'always') {\n var wordSeparators = getMapForWordSeparators(config.wordSeparators);\n var characterBeforeCode = lineText.charCodeAt(position.column - 2);\n var characterBeforeType = wordSeparators.get(characterBeforeCode);\n if (characterBeforeType === 0 /* Regular */) {\n return false;\n }\n }\n // Only consider auto closing the pair if a space follows or if another autoclosed pair follows\n var characterAfter = lineText.charAt(position.column - 1);\n if (characterAfter) {\n var isBeforeCloseBrace = TypeOperations._isBeforeClosingBrace(config, ch, characterAfter);\n if (!isBeforeCloseBrace && !shouldAutoCloseBefore(characterAfter)) {\n return false;\n }\n }\n if (!model.isCheapToTokenize(position.lineNumber)) {\n // Do not force tokenization\n return false;\n }\n model.forceTokenization(position.lineNumber);\n var lineTokens = model.getLineTokens(position.lineNumber);\n var shouldAutoClosePair = false;\n try {\n shouldAutoClosePair = LanguageConfigurationRegistry.shouldAutoClosePair(ch, lineTokens, position.column);\n }\n catch (e) {\n onUnexpectedError(e);\n }\n if (!shouldAutoClosePair) {\n return false;\n }\n }\n return true;\n };\n TypeOperations._runAutoClosingOpenCharType = function (prevEditOperationType, config, model, selections, ch) {\n var commands = [];\n for (var i = 0, len = selections.length; i < len; i++) {\n var selection = selections[i];\n var closeCharacter = config.autoClosingPairsOpen[ch];\n commands[i] = new ReplaceCommandWithOffsetCursorState(selection, ch + closeCharacter, 0, -closeCharacter.length);\n }\n return new EditOperationResult(1 /* Typing */, commands, {\n shouldPushStackElementBefore: true,\n shouldPushStackElementAfter: false\n });\n };\n TypeOperations._shouldSurroundChar = function (config, ch) {\n if (isQuote(ch)) {\n return (config.autoSurround === 'quotes' || config.autoSurround === 'languageDefined');\n }\n else {\n // Character is a bracket\n return (config.autoSurround === 'brackets' || config.autoSurround === 'languageDefined');\n }\n };\n TypeOperations._isSurroundSelectionType = function (config, model, selections, ch) {\n if (!TypeOperations._shouldSurroundChar(config, ch) || !config.surroundingPairs.hasOwnProperty(ch)) {\n return false;\n }\n var isTypingAQuoteCharacter = isQuote(ch);\n for (var i = 0, len = selections.length; i < len; i++) {\n var selection = selections[i];\n if (selection.isEmpty()) {\n return false;\n }\n var selectionContainsOnlyWhitespace = true;\n for (var lineNumber = selection.startLineNumber; lineNumber <= selection.endLineNumber; lineNumber++) {\n var lineText = model.getLineContent(lineNumber);\n var startIndex = (lineNumber === selection.startLineNumber ? selection.startColumn - 1 : 0);\n var endIndex = (lineNumber === selection.endLineNumber ? selection.endColumn - 1 : lineText.length);\n var selectedText = lineText.substring(startIndex, endIndex);\n if (/[^ \\t]/.test(selectedText)) {\n // this selected text contains something other than whitespace\n selectionContainsOnlyWhitespace = false;\n break;\n }\n }\n if (selectionContainsOnlyWhitespace) {\n return false;\n }\n if (isTypingAQuoteCharacter && selection.startLineNumber === selection.endLineNumber && selection.startColumn + 1 === selection.endColumn) {\n var selectionText = model.getValueInRange(selection);\n if (isQuote(selectionText)) {\n // Typing a quote character on top of another quote character\n // => disable surround selection type\n return false;\n }\n }\n }\n return true;\n };\n TypeOperations._runSurroundSelectionType = function (prevEditOperationType, config, model, selections, ch) {\n var commands = [];\n for (var i = 0, len = selections.length; i < len; i++) {\n var selection = selections[i];\n var closeCharacter = config.surroundingPairs[ch];\n commands[i] = new SurroundSelectionCommand(selection, ch, closeCharacter);\n }\n return new EditOperationResult(0 /* Other */, commands, {\n shouldPushStackElementBefore: true,\n shouldPushStackElementAfter: true\n });\n };\n TypeOperations._isTypeInterceptorElectricChar = function (config, model, selections) {\n if (selections.length === 1 && model.isCheapToTokenize(selections[0].getEndPosition().lineNumber)) {\n return true;\n }\n return false;\n };\n TypeOperations._typeInterceptorElectricChar = function (prevEditOperationType, config, model, selection, ch) {\n if (!config.electricChars.hasOwnProperty(ch) || !selection.isEmpty()) {\n return null;\n }\n var position = selection.getPosition();\n model.forceTokenization(position.lineNumber);\n var lineTokens = model.getLineTokens(position.lineNumber);\n var electricAction;\n try {\n electricAction = LanguageConfigurationRegistry.onElectricCharacter(ch, lineTokens, position.column);\n }\n catch (e) {\n onUnexpectedError(e);\n return null;\n }\n if (!electricAction) {\n return null;\n }\n if (electricAction.appendText) {\n var command = new ReplaceCommandWithOffsetCursorState(selection, ch + electricAction.appendText, 0, -electricAction.appendText.length);\n return new EditOperationResult(1 /* Typing */, [command], {\n shouldPushStackElementBefore: false,\n shouldPushStackElementAfter: true\n });\n }\n if (electricAction.matchOpenBracket) {\n var endColumn = (lineTokens.getLineContent() + ch).lastIndexOf(electricAction.matchOpenBracket) + 1;\n var match = model.findMatchingBracketUp(electricAction.matchOpenBracket, {\n lineNumber: position.lineNumber,\n column: endColumn\n });\n if (match) {\n if (match.startLineNumber === position.lineNumber) {\n // matched something on the same line => no change in indentation\n return null;\n }\n var matchLine = model.getLineContent(match.startLineNumber);\n var matchLineIndentation = strings.getLeadingWhitespace(matchLine);\n var newIndentation = config.normalizeIndentation(matchLineIndentation);\n var lineText = model.getLineContent(position.lineNumber);\n var lineFirstNonBlankColumn = model.getLineFirstNonWhitespaceColumn(position.lineNumber) || position.column;\n var prefix = lineText.substring(lineFirstNonBlankColumn - 1, position.column - 1);\n var typeText = newIndentation + prefix + ch;\n var typeSelection = new Range(position.lineNumber, 1, position.lineNumber, position.column);\n var command = new ReplaceCommand(typeSelection, typeText);\n return new EditOperationResult(1 /* Typing */, [command], {\n shouldPushStackElementBefore: false,\n shouldPushStackElementAfter: true\n });\n }\n }\n return null;\n };\n TypeOperations.compositionEndWithInterceptors = function (prevEditOperationType, config, model, selections) {\n if (config.autoClosingQuotes === 'never') {\n return null;\n }\n var commands = [];\n for (var i = 0; i < selections.length; i++) {\n if (!selections[i].isEmpty()) {\n continue;\n }\n var position = selections[i].getPosition();\n var lineText = model.getLineContent(position.lineNumber);\n var ch = lineText.charAt(position.column - 2);\n if (config.autoClosingPairsClose.hasOwnProperty(ch)) { // first of all, it's a closing tag\n if (ch === config.autoClosingPairsClose[ch] /** isEqualPair */) {\n var lineTextBeforeCursor = lineText.substr(0, position.column - 2);\n var chCntBefore = this._countNeedlesInHaystack(lineTextBeforeCursor, ch);\n if (chCntBefore % 2 === 1) {\n continue; // it pairs with the opening tag.\n }\n }\n }\n // As we are not typing in a new character, so we don't need to run `_runAutoClosingCloseCharType`\n // Next step, let's try to check if it's an open char.\n if (config.autoClosingPairsOpen.hasOwnProperty(ch)) {\n if (isQuote(ch) && position.column > 2) {\n var wordSeparators = getMapForWordSeparators(config.wordSeparators);\n var characterBeforeCode = lineText.charCodeAt(position.column - 3);\n var characterBeforeType = wordSeparators.get(characterBeforeCode);\n if (characterBeforeType === 0 /* Regular */) {\n continue;\n }\n }\n var characterAfter = lineText.charAt(position.column - 1);\n if (characterAfter) {\n var isBeforeCloseBrace = TypeOperations._isBeforeClosingBrace(config, ch, characterAfter);\n var shouldAutoCloseBefore = isQuote(ch) ? config.shouldAutoCloseBefore.quote : config.shouldAutoCloseBefore.bracket;\n if (isBeforeCloseBrace) {\n // In normal auto closing logic, we will auto close if the cursor is even before a closing brace intentionally.\n // However for composition mode, we do nothing here as users might clear all the characters for composition and we don't want to do a unnecessary auto close.\n // Related: microsoft/vscode#57250.\n continue;\n }\n if (!shouldAutoCloseBefore(characterAfter)) {\n continue;\n }\n }\n if (!model.isCheapToTokenize(position.lineNumber)) {\n // Do not force tokenization\n continue;\n }\n model.forceTokenization(position.lineNumber);\n var lineTokens = model.getLineTokens(position.lineNumber);\n var shouldAutoClosePair = false;\n try {\n shouldAutoClosePair = LanguageConfigurationRegistry.shouldAutoClosePair(ch, lineTokens, position.column - 1);\n }\n catch (e) {\n onUnexpectedError(e);\n }\n if (shouldAutoClosePair) {\n var closeCharacter = config.autoClosingPairsOpen[ch];\n commands[i] = new ReplaceCommandWithOffsetCursorState(selections[i], closeCharacter, 0, -closeCharacter.length);\n }\n }\n }\n return new EditOperationResult(1 /* Typing */, commands, {\n shouldPushStackElementBefore: true,\n shouldPushStackElementAfter: false\n });\n };\n TypeOperations.typeWithInterceptors = function (prevEditOperationType, config, model, selections, ch) {\n if (ch === '\\n') {\n var commands_1 = [];\n for (var i = 0, len = selections.length; i < len; i++) {\n commands_1[i] = TypeOperations._enter(config, model, false, selections[i]);\n }\n return new EditOperationResult(1 /* Typing */, commands_1, {\n shouldPushStackElementBefore: true,\n shouldPushStackElementAfter: false,\n });\n }\n if (this._isAutoIndentType(config, model, selections)) {\n var commands_2 = [];\n var autoIndentFails = false;\n for (var i = 0, len = selections.length; i < len; i++) {\n commands_2[i] = this._runAutoIndentType(config, model, selections[i], ch);\n if (!commands_2[i]) {\n autoIndentFails = true;\n break;\n }\n }\n if (!autoIndentFails) {\n return new EditOperationResult(1 /* Typing */, commands_2, {\n shouldPushStackElementBefore: true,\n shouldPushStackElementAfter: false,\n });\n }\n }\n if (this._isAutoClosingCloseCharType(config, model, selections, ch)) {\n return this._runAutoClosingCloseCharType(prevEditOperationType, config, model, selections, ch);\n }\n if (this._isAutoClosingOpenCharType(config, model, selections, ch)) {\n return this._runAutoClosingOpenCharType(prevEditOperationType, config, model, selections, ch);\n }\n if (this._isSurroundSelectionType(config, model, selections, ch)) {\n return this._runSurroundSelectionType(prevEditOperationType, config, model, selections, ch);\n }\n // Electric characters make sense only when dealing with a single cursor,\n // as multiple cursors typing brackets for example would interfer with bracket matching\n if (this._isTypeInterceptorElectricChar(config, model, selections)) {\n var r = this._typeInterceptorElectricChar(prevEditOperationType, config, model, selections[0], ch);\n if (r) {\n return r;\n }\n }\n // A simple character type\n var commands = [];\n for (var i = 0, len = selections.length; i < len; i++) {\n commands[i] = new ReplaceCommand(selections[i], ch);\n }\n var shouldPushStackElementBefore = (prevEditOperationType !== 1 /* Typing */);\n if (ch === ' ') {\n shouldPushStackElementBefore = true;\n }\n return new EditOperationResult(1 /* Typing */, commands, {\n shouldPushStackElementBefore: shouldPushStackElementBefore,\n shouldPushStackElementAfter: false\n });\n };\n TypeOperations.typeWithoutInterceptors = function (prevEditOperationType, config, model, selections, str) {\n var commands = [];\n for (var i = 0, len = selections.length; i < len; i++) {\n commands[i] = new ReplaceCommand(selections[i], str);\n }\n return new EditOperationResult(1 /* Typing */, commands, {\n shouldPushStackElementBefore: (prevEditOperationType !== 1 /* Typing */),\n shouldPushStackElementAfter: false\n });\n };\n TypeOperations.lineInsertBefore = function (config, model, selections) {\n if (model === null || selections === null) {\n return [];\n }\n var commands = [];\n for (var i = 0, len = selections.length; i < len; i++) {\n var lineNumber = selections[i].positionLineNumber;\n if (lineNumber === 1) {\n commands[i] = new ReplaceCommandWithoutChangingPosition(new Range(1, 1, 1, 1), '\\n');\n }\n else {\n lineNumber--;\n var column = model.getLineMaxColumn(lineNumber);\n commands[i] = this._enter(config, model, false, new Range(lineNumber, column, lineNumber, column));\n }\n }\n return commands;\n };\n TypeOperations.lineInsertAfter = function (config, model, selections) {\n if (model === null || selections === null) {\n return [];\n }\n var commands = [];\n for (var i = 0, len = selections.length; i < len; i++) {\n var lineNumber = selections[i].positionLineNumber;\n var column = model.getLineMaxColumn(lineNumber);\n commands[i] = this._enter(config, model, false, new Range(lineNumber, column, lineNumber, column));\n }\n return commands;\n };\n TypeOperations.lineBreakInsert = function (config, model, selections) {\n var commands = [];\n for (var i = 0, len = selections.length; i < len; i++) {\n commands[i] = this._enter(config, model, true, selections[i]);\n }\n return commands;\n };\n return TypeOperations;\n}());\nexport { TypeOperations };\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport * as nls from '../../../nls.js';\nimport * as types from '../../../base/common/types.js';\nimport { Command, EditorCommand, registerEditorCommand } from '../editorExtensions.js';\nimport { ICodeEditorService } from '../services/codeEditorService.js';\nimport { ColumnSelection } from '../../common/controller/cursorColumnSelection.js';\nimport { CursorState } from '../../common/controller/cursorCommon.js';\nimport { DeleteOperations } from '../../common/controller/cursorDeleteOperations.js';\nimport { CursorMove as CursorMove_, CursorMoveCommands } from '../../common/controller/cursorMoveCommands.js';\nimport { TypeOperations } from '../../common/controller/cursorTypeOperations.js';\nimport { Position } from '../../common/core/position.js';\nimport { Range } from '../../common/core/range.js';\nimport { Handler } from '../../common/editorCommon.js';\nimport { EditorContextKeys } from '../../common/editorContextKeys.js';\nimport { ContextKeyExpr } from '../../../platform/contextkey/common/contextkey.js';\nvar CORE_WEIGHT = 0 /* EditorCore */;\nvar CoreEditorCommand = /** @class */ (function (_super) {\n __extends(CoreEditorCommand, _super);\n function CoreEditorCommand() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n CoreEditorCommand.prototype.runEditorCommand = function (accessor, editor, args) {\n var cursors = editor._getCursors();\n if (!cursors) {\n // the editor has no view => has no cursors\n return;\n }\n this.runCoreEditorCommand(cursors, args || {});\n };\n return CoreEditorCommand;\n}(EditorCommand));\nexport { CoreEditorCommand };\nexport var EditorScroll_;\n(function (EditorScroll_) {\n var isEditorScrollArgs = function (arg) {\n if (!types.isObject(arg)) {\n return false;\n }\n var scrollArg = arg;\n if (!types.isString(scrollArg.to)) {\n return false;\n }\n if (!types.isUndefined(scrollArg.by) && !types.isString(scrollArg.by)) {\n return false;\n }\n if (!types.isUndefined(scrollArg.value) && !types.isNumber(scrollArg.value)) {\n return false;\n }\n if (!types.isUndefined(scrollArg.revealCursor) && !types.isBoolean(scrollArg.revealCursor)) {\n return false;\n }\n return true;\n };\n EditorScroll_.description = {\n description: 'Scroll editor in the given direction',\n args: [\n {\n name: 'Editor scroll argument object',\n description: \"Property-value pairs that can be passed through this argument:\\n\\t\\t\\t\\t\\t* 'to': A mandatory direction value.\\n\\t\\t\\t\\t\\t\\t```\\n\\t\\t\\t\\t\\t\\t'up', 'down'\\n\\t\\t\\t\\t\\t\\t```\\n\\t\\t\\t\\t\\t* 'by': Unit to move. Default is computed based on 'to' value.\\n\\t\\t\\t\\t\\t\\t```\\n\\t\\t\\t\\t\\t\\t'line', 'wrappedLine', 'page', 'halfPage'\\n\\t\\t\\t\\t\\t\\t```\\n\\t\\t\\t\\t\\t* 'value': Number of units to move. Default is '1'.\\n\\t\\t\\t\\t\\t* 'revealCursor': If 'true' reveals the cursor if it is outside view port.\\n\\t\\t\\t\\t\",\n constraint: isEditorScrollArgs,\n schema: {\n 'type': 'object',\n 'required': ['to'],\n 'properties': {\n 'to': {\n 'type': 'string',\n 'enum': ['up', 'down']\n },\n 'by': {\n 'type': 'string',\n 'enum': ['line', 'wrappedLine', 'page', 'halfPage']\n },\n 'value': {\n 'type': 'number',\n 'default': 1\n },\n 'revealCursor': {\n 'type': 'boolean',\n }\n }\n }\n }\n ]\n };\n /**\n * Directions in the view for editor scroll command.\n */\n EditorScroll_.RawDirection = {\n Up: 'up',\n Down: 'down',\n };\n /**\n * Units for editor scroll 'by' argument\n */\n EditorScroll_.RawUnit = {\n Line: 'line',\n WrappedLine: 'wrappedLine',\n Page: 'page',\n HalfPage: 'halfPage'\n };\n function parse(args) {\n var direction;\n switch (args.to) {\n case EditorScroll_.RawDirection.Up:\n direction = 1 /* Up */;\n break;\n case EditorScroll_.RawDirection.Down:\n direction = 2 /* Down */;\n break;\n default:\n // Illegal arguments\n return null;\n }\n var unit;\n switch (args.by) {\n case EditorScroll_.RawUnit.Line:\n unit = 1 /* Line */;\n break;\n case EditorScroll_.RawUnit.WrappedLine:\n unit = 2 /* WrappedLine */;\n break;\n case EditorScroll_.RawUnit.Page:\n unit = 3 /* Page */;\n break;\n case EditorScroll_.RawUnit.HalfPage:\n unit = 4 /* HalfPage */;\n break;\n default:\n unit = 2 /* WrappedLine */;\n }\n var value = Math.floor(args.value || 1);\n var revealCursor = !!args.revealCursor;\n return {\n direction: direction,\n unit: unit,\n value: value,\n revealCursor: revealCursor,\n select: (!!args.select)\n };\n }\n EditorScroll_.parse = parse;\n})(EditorScroll_ || (EditorScroll_ = {}));\nexport var RevealLine_;\n(function (RevealLine_) {\n var isRevealLineArgs = function (arg) {\n if (!types.isObject(arg)) {\n return false;\n }\n var reveaLineArg = arg;\n if (!types.isNumber(reveaLineArg.lineNumber)) {\n return false;\n }\n if (!types.isUndefined(reveaLineArg.at) && !types.isString(reveaLineArg.at)) {\n return false;\n }\n return true;\n };\n RevealLine_.description = {\n description: 'Reveal the given line at the given logical position',\n args: [\n {\n name: 'Reveal line argument object',\n description: \"Property-value pairs that can be passed through this argument:\\n\\t\\t\\t\\t\\t* 'lineNumber': A mandatory line number value.\\n\\t\\t\\t\\t\\t* 'at': Logical position at which line has to be revealed .\\n\\t\\t\\t\\t\\t\\t```\\n\\t\\t\\t\\t\\t\\t'top', 'center', 'bottom'\\n\\t\\t\\t\\t\\t\\t```\\n\\t\\t\\t\\t\",\n constraint: isRevealLineArgs,\n schema: {\n 'type': 'object',\n 'required': ['lineNumber'],\n 'properties': {\n 'lineNumber': {\n 'type': 'number',\n },\n 'at': {\n 'type': 'string',\n 'enum': ['top', 'center', 'bottom']\n }\n }\n }\n }\n ]\n };\n /**\n * Values for reveal line 'at' argument\n */\n RevealLine_.RawAtArgument = {\n Top: 'top',\n Center: 'center',\n Bottom: 'bottom'\n };\n})(RevealLine_ || (RevealLine_ = {}));\nexport var CoreNavigationCommands;\n(function (CoreNavigationCommands) {\n var BaseMoveToCommand = /** @class */ (function (_super) {\n __extends(BaseMoveToCommand, _super);\n function BaseMoveToCommand(opts) {\n var _this = _super.call(this, opts) || this;\n _this._inSelectionMode = opts.inSelectionMode;\n return _this;\n }\n BaseMoveToCommand.prototype.runCoreEditorCommand = function (cursors, args) {\n cursors.context.model.pushStackElement();\n cursors.setStates(args.source, 3 /* Explicit */, [\n CursorMoveCommands.moveTo(cursors.context, cursors.getPrimaryCursor(), this._inSelectionMode, args.position, args.viewPosition)\n ]);\n cursors.reveal(true, 0 /* Primary */, 0 /* Smooth */);\n };\n return BaseMoveToCommand;\n }(CoreEditorCommand));\n CoreNavigationCommands.MoveTo = registerEditorCommand(new BaseMoveToCommand({\n id: '_moveTo',\n inSelectionMode: false,\n precondition: null\n }));\n CoreNavigationCommands.MoveToSelect = registerEditorCommand(new BaseMoveToCommand({\n id: '_moveToSelect',\n inSelectionMode: true,\n precondition: null\n }));\n var ColumnSelectCommand = /** @class */ (function (_super) {\n __extends(ColumnSelectCommand, _super);\n function ColumnSelectCommand() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n ColumnSelectCommand.prototype.runCoreEditorCommand = function (cursors, args) {\n cursors.context.model.pushStackElement();\n var result = this._getColumnSelectResult(cursors.context, cursors.getPrimaryCursor(), cursors.getColumnSelectData(), args);\n cursors.setStates(args.source, 3 /* Explicit */, result.viewStates.map(function (viewState) { return CursorState.fromViewState(viewState); }));\n cursors.setColumnSelectData({\n toViewLineNumber: result.toLineNumber,\n toViewVisualColumn: result.toVisualColumn\n });\n cursors.reveal(true, (result.reversed ? 1 /* TopMost */ : 2 /* BottomMost */), 0 /* Smooth */);\n };\n return ColumnSelectCommand;\n }(CoreEditorCommand));\n CoreNavigationCommands.ColumnSelect = registerEditorCommand(new /** @class */ (function (_super) {\n __extends(class_1, _super);\n function class_1() {\n return _super.call(this, {\n id: 'columnSelect',\n precondition: null\n }) || this;\n }\n class_1.prototype._getColumnSelectResult = function (context, primary, prevColumnSelectData, args) {\n // validate `args`\n var validatedPosition = context.model.validatePosition(args.position);\n var validatedViewPosition;\n if (args.viewPosition) {\n validatedViewPosition = context.validateViewPosition(new Position(args.viewPosition.lineNumber, args.viewPosition.column), validatedPosition);\n }\n else {\n validatedViewPosition = context.convertModelPositionToViewPosition(validatedPosition);\n }\n return ColumnSelection.columnSelect(context.config, context.viewModel, primary.viewState.selection, validatedViewPosition.lineNumber, args.mouseColumn - 1);\n };\n return class_1;\n }(ColumnSelectCommand)));\n CoreNavigationCommands.CursorColumnSelectLeft = registerEditorCommand(new /** @class */ (function (_super) {\n __extends(class_2, _super);\n function class_2() {\n return _super.call(this, {\n id: 'cursorColumnSelectLeft',\n precondition: null,\n kbOpts: {\n weight: CORE_WEIGHT,\n kbExpr: EditorContextKeys.textInputFocus,\n primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 512 /* Alt */ | 15 /* LeftArrow */,\n linux: { primary: 0 }\n }\n }) || this;\n }\n class_2.prototype._getColumnSelectResult = function (context, primary, prevColumnSelectData, args) {\n return ColumnSelection.columnSelectLeft(context.config, context.viewModel, primary.viewState, prevColumnSelectData.toViewLineNumber, prevColumnSelectData.toViewVisualColumn);\n };\n return class_2;\n }(ColumnSelectCommand)));\n CoreNavigationCommands.CursorColumnSelectRight = registerEditorCommand(new /** @class */ (function (_super) {\n __extends(class_3, _super);\n function class_3() {\n return _super.call(this, {\n id: 'cursorColumnSelectRight',\n precondition: null,\n kbOpts: {\n weight: CORE_WEIGHT,\n kbExpr: EditorContextKeys.textInputFocus,\n primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 512 /* Alt */ | 17 /* RightArrow */,\n linux: { primary: 0 }\n }\n }) || this;\n }\n class_3.prototype._getColumnSelectResult = function (context, primary, prevColumnSelectData, args) {\n return ColumnSelection.columnSelectRight(context.config, context.viewModel, primary.viewState, prevColumnSelectData.toViewLineNumber, prevColumnSelectData.toViewVisualColumn);\n };\n return class_3;\n }(ColumnSelectCommand)));\n var ColumnSelectUpCommand = /** @class */ (function (_super) {\n __extends(ColumnSelectUpCommand, _super);\n function ColumnSelectUpCommand(opts) {\n var _this = _super.call(this, opts) || this;\n _this._isPaged = opts.isPaged;\n return _this;\n }\n ColumnSelectUpCommand.prototype._getColumnSelectResult = function (context, primary, prevColumnSelectData, args) {\n return ColumnSelection.columnSelectUp(context.config, context.viewModel, primary.viewState, this._isPaged, prevColumnSelectData.toViewLineNumber, prevColumnSelectData.toViewVisualColumn);\n };\n return ColumnSelectUpCommand;\n }(ColumnSelectCommand));\n CoreNavigationCommands.CursorColumnSelectUp = registerEditorCommand(new ColumnSelectUpCommand({\n isPaged: false,\n id: 'cursorColumnSelectUp',\n precondition: null,\n kbOpts: {\n weight: CORE_WEIGHT,\n kbExpr: EditorContextKeys.textInputFocus,\n primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 512 /* Alt */ | 16 /* UpArrow */,\n linux: { primary: 0 }\n }\n }));\n CoreNavigationCommands.CursorColumnSelectPageUp = registerEditorCommand(new ColumnSelectUpCommand({\n isPaged: true,\n id: 'cursorColumnSelectPageUp',\n precondition: null,\n kbOpts: {\n weight: CORE_WEIGHT,\n kbExpr: EditorContextKeys.textInputFocus,\n primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 512 /* Alt */ | 11 /* PageUp */,\n linux: { primary: 0 }\n }\n }));\n var ColumnSelectDownCommand = /** @class */ (function (_super) {\n __extends(ColumnSelectDownCommand, _super);\n function ColumnSelectDownCommand(opts) {\n var _this = _super.call(this, opts) || this;\n _this._isPaged = opts.isPaged;\n return _this;\n }\n ColumnSelectDownCommand.prototype._getColumnSelectResult = function (context, primary, prevColumnSelectData, args) {\n return ColumnSelection.columnSelectDown(context.config, context.viewModel, primary.viewState, this._isPaged, prevColumnSelectData.toViewLineNumber, prevColumnSelectData.toViewVisualColumn);\n };\n return ColumnSelectDownCommand;\n }(ColumnSelectCommand));\n CoreNavigationCommands.CursorColumnSelectDown = registerEditorCommand(new ColumnSelectDownCommand({\n isPaged: false,\n id: 'cursorColumnSelectDown',\n precondition: null,\n kbOpts: {\n weight: CORE_WEIGHT,\n kbExpr: EditorContextKeys.textInputFocus,\n primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 512 /* Alt */ | 18 /* DownArrow */,\n linux: { primary: 0 }\n }\n }));\n CoreNavigationCommands.CursorColumnSelectPageDown = registerEditorCommand(new ColumnSelectDownCommand({\n isPaged: true,\n id: 'cursorColumnSelectPageDown',\n precondition: null,\n kbOpts: {\n weight: CORE_WEIGHT,\n kbExpr: EditorContextKeys.textInputFocus,\n primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 512 /* Alt */ | 12 /* PageDown */,\n linux: { primary: 0 }\n }\n }));\n var CursorMoveImpl = /** @class */ (function (_super) {\n __extends(CursorMoveImpl, _super);\n function CursorMoveImpl() {\n return _super.call(this, {\n id: 'cursorMove',\n precondition: null,\n description: CursorMove_.description\n }) || this;\n }\n CursorMoveImpl.prototype.runCoreEditorCommand = function (cursors, args) {\n var parsed = CursorMove_.parse(args);\n if (!parsed) {\n // illegal arguments\n return;\n }\n this._runCursorMove(cursors, args.source, parsed);\n };\n CursorMoveImpl.prototype._runCursorMove = function (cursors, source, args) {\n cursors.context.model.pushStackElement();\n cursors.setStates(source, 3 /* Explicit */, CursorMoveCommands.move(cursors.context, cursors.getAll(), args));\n cursors.reveal(true, 0 /* Primary */, 0 /* Smooth */);\n };\n return CursorMoveImpl;\n }(CoreEditorCommand));\n CoreNavigationCommands.CursorMoveImpl = CursorMoveImpl;\n CoreNavigationCommands.CursorMove = registerEditorCommand(new CursorMoveImpl());\n var CursorMoveBasedCommand = /** @class */ (function (_super) {\n __extends(CursorMoveBasedCommand, _super);\n function CursorMoveBasedCommand(opts) {\n var _this = _super.call(this, opts) || this;\n _this._staticArgs = opts.args;\n return _this;\n }\n CursorMoveBasedCommand.prototype.runCoreEditorCommand = function (cursors, dynamicArgs) {\n var args = this._staticArgs;\n if (this._staticArgs.value === -1 /* PAGE_SIZE_MARKER */) {\n // -1 is a marker for page size\n args = {\n direction: this._staticArgs.direction,\n unit: this._staticArgs.unit,\n select: this._staticArgs.select,\n value: cursors.context.config.pageSize\n };\n }\n CoreNavigationCommands.CursorMove._runCursorMove(cursors, dynamicArgs.source, args);\n };\n return CursorMoveBasedCommand;\n }(CoreEditorCommand));\n CoreNavigationCommands.CursorLeft = registerEditorCommand(new CursorMoveBasedCommand({\n args: {\n direction: 0 /* Left */,\n unit: 0 /* None */,\n select: false,\n value: 1\n },\n id: 'cursorLeft',\n precondition: null,\n kbOpts: {\n weight: CORE_WEIGHT,\n kbExpr: EditorContextKeys.textInputFocus,\n primary: 15 /* LeftArrow */,\n mac: { primary: 15 /* LeftArrow */, secondary: [256 /* WinCtrl */ | 32 /* KEY_B */] }\n }\n }));\n CoreNavigationCommands.CursorLeftSelect = registerEditorCommand(new CursorMoveBasedCommand({\n args: {\n direction: 0 /* Left */,\n unit: 0 /* None */,\n select: true,\n value: 1\n },\n id: 'cursorLeftSelect',\n precondition: null,\n kbOpts: {\n weight: CORE_WEIGHT,\n kbExpr: EditorContextKeys.textInputFocus,\n primary: 1024 /* Shift */ | 15 /* LeftArrow */\n }\n }));\n CoreNavigationCommands.CursorRight = registerEditorCommand(new CursorMoveBasedCommand({\n args: {\n direction: 1 /* Right */,\n unit: 0 /* None */,\n select: false,\n value: 1\n },\n id: 'cursorRight',\n precondition: null,\n kbOpts: {\n weight: CORE_WEIGHT,\n kbExpr: EditorContextKeys.textInputFocus,\n primary: 17 /* RightArrow */,\n mac: { primary: 17 /* RightArrow */, secondary: [256 /* WinCtrl */ | 36 /* KEY_F */] }\n }\n }));\n CoreNavigationCommands.CursorRightSelect = registerEditorCommand(new CursorMoveBasedCommand({\n args: {\n direction: 1 /* Right */,\n unit: 0 /* None */,\n select: true,\n value: 1\n },\n id: 'cursorRightSelect',\n precondition: null,\n kbOpts: {\n weight: CORE_WEIGHT,\n kbExpr: EditorContextKeys.textInputFocus,\n primary: 1024 /* Shift */ | 17 /* RightArrow */\n }\n }));\n CoreNavigationCommands.CursorUp = registerEditorCommand(new CursorMoveBasedCommand({\n args: {\n direction: 2 /* Up */,\n unit: 2 /* WrappedLine */,\n select: false,\n value: 1\n },\n id: 'cursorUp',\n precondition: null,\n kbOpts: {\n weight: CORE_WEIGHT,\n kbExpr: EditorContextKeys.textInputFocus,\n primary: 16 /* UpArrow */,\n mac: { primary: 16 /* UpArrow */, secondary: [256 /* WinCtrl */ | 46 /* KEY_P */] }\n }\n }));\n CoreNavigationCommands.CursorUpSelect = registerEditorCommand(new CursorMoveBasedCommand({\n args: {\n direction: 2 /* Up */,\n unit: 2 /* WrappedLine */,\n select: true,\n value: 1\n },\n id: 'cursorUpSelect',\n precondition: null,\n kbOpts: {\n weight: CORE_WEIGHT,\n kbExpr: EditorContextKeys.textInputFocus,\n primary: 1024 /* Shift */ | 16 /* UpArrow */,\n secondary: [2048 /* CtrlCmd */ | 1024 /* Shift */ | 16 /* UpArrow */],\n mac: { primary: 1024 /* Shift */ | 16 /* UpArrow */ },\n linux: { primary: 1024 /* Shift */ | 16 /* UpArrow */ }\n }\n }));\n CoreNavigationCommands.CursorPageUp = registerEditorCommand(new CursorMoveBasedCommand({\n args: {\n direction: 2 /* Up */,\n unit: 2 /* WrappedLine */,\n select: false,\n value: -1 /* PAGE_SIZE_MARKER */\n },\n id: 'cursorPageUp',\n precondition: null,\n kbOpts: {\n weight: CORE_WEIGHT,\n kbExpr: EditorContextKeys.textInputFocus,\n primary: 11 /* PageUp */\n }\n }));\n CoreNavigationCommands.CursorPageUpSelect = registerEditorCommand(new CursorMoveBasedCommand({\n args: {\n direction: 2 /* Up */,\n unit: 2 /* WrappedLine */,\n select: true,\n value: -1 /* PAGE_SIZE_MARKER */\n },\n id: 'cursorPageUpSelect',\n precondition: null,\n kbOpts: {\n weight: CORE_WEIGHT,\n kbExpr: EditorContextKeys.textInputFocus,\n primary: 1024 /* Shift */ | 11 /* PageUp */\n }\n }));\n CoreNavigationCommands.CursorDown = registerEditorCommand(new CursorMoveBasedCommand({\n args: {\n direction: 3 /* Down */,\n unit: 2 /* WrappedLine */,\n select: false,\n value: 1\n },\n id: 'cursorDown',\n precondition: null,\n kbOpts: {\n weight: CORE_WEIGHT,\n kbExpr: EditorContextKeys.textInputFocus,\n primary: 18 /* DownArrow */,\n mac: { primary: 18 /* DownArrow */, secondary: [256 /* WinCtrl */ | 44 /* KEY_N */] }\n }\n }));\n CoreNavigationCommands.CursorDownSelect = registerEditorCommand(new CursorMoveBasedCommand({\n args: {\n direction: 3 /* Down */,\n unit: 2 /* WrappedLine */,\n select: true,\n value: 1\n },\n id: 'cursorDownSelect',\n precondition: null,\n kbOpts: {\n weight: CORE_WEIGHT,\n kbExpr: EditorContextKeys.textInputFocus,\n primary: 1024 /* Shift */ | 18 /* DownArrow */,\n secondary: [2048 /* CtrlCmd */ | 1024 /* Shift */ | 18 /* DownArrow */],\n mac: { primary: 1024 /* Shift */ | 18 /* DownArrow */ },\n linux: { primary: 1024 /* Shift */ | 18 /* DownArrow */ }\n }\n }));\n CoreNavigationCommands.CursorPageDown = registerEditorCommand(new CursorMoveBasedCommand({\n args: {\n direction: 3 /* Down */,\n unit: 2 /* WrappedLine */,\n select: false,\n value: -1 /* PAGE_SIZE_MARKER */\n },\n id: 'cursorPageDown',\n precondition: null,\n kbOpts: {\n weight: CORE_WEIGHT,\n kbExpr: EditorContextKeys.textInputFocus,\n primary: 12 /* PageDown */\n }\n }));\n CoreNavigationCommands.CursorPageDownSelect = registerEditorCommand(new CursorMoveBasedCommand({\n args: {\n direction: 3 /* Down */,\n unit: 2 /* WrappedLine */,\n select: true,\n value: -1 /* PAGE_SIZE_MARKER */\n },\n id: 'cursorPageDownSelect',\n precondition: null,\n kbOpts: {\n weight: CORE_WEIGHT,\n kbExpr: EditorContextKeys.textInputFocus,\n primary: 1024 /* Shift */ | 12 /* PageDown */\n }\n }));\n CoreNavigationCommands.CreateCursor = registerEditorCommand(new /** @class */ (function (_super) {\n __extends(class_4, _super);\n function class_4() {\n return _super.call(this, {\n id: 'createCursor',\n precondition: null\n }) || this;\n }\n class_4.prototype.runCoreEditorCommand = function (cursors, args) {\n var context = cursors.context;\n var newState;\n if (args.wholeLine) {\n newState = CursorMoveCommands.line(context, cursors.getPrimaryCursor(), false, args.position, args.viewPosition);\n }\n else {\n newState = CursorMoveCommands.moveTo(context, cursors.getPrimaryCursor(), false, args.position, args.viewPosition);\n }\n var states = cursors.getAll();\n // Check if we should remove a cursor (sort of like a toggle)\n if (states.length > 1) {\n var newModelPosition = (newState.modelState ? newState.modelState.position : null);\n var newViewPosition = (newState.viewState ? newState.viewState.position : null);\n for (var i = 0, len = states.length; i < len; i++) {\n var state = states[i];\n if (newModelPosition && !state.modelState.selection.containsPosition(newModelPosition)) {\n continue;\n }\n if (newViewPosition && !state.viewState.selection.containsPosition(newViewPosition)) {\n continue;\n }\n // => Remove the cursor\n states.splice(i, 1);\n cursors.context.model.pushStackElement();\n cursors.setStates(args.source, 3 /* Explicit */, states);\n return;\n }\n }\n // => Add the new cursor\n states.push(newState);\n cursors.context.model.pushStackElement();\n cursors.setStates(args.source, 3 /* Explicit */, states);\n };\n return class_4;\n }(CoreEditorCommand)));\n CoreNavigationCommands.LastCursorMoveToSelect = registerEditorCommand(new /** @class */ (function (_super) {\n __extends(class_5, _super);\n function class_5() {\n return _super.call(this, {\n id: '_lastCursorMoveToSelect',\n precondition: null\n }) || this;\n }\n class_5.prototype.runCoreEditorCommand = function (cursors, args) {\n var context = cursors.context;\n var lastAddedCursorIndex = cursors.getLastAddedCursorIndex();\n var states = cursors.getAll();\n var newStates = states.slice(0);\n newStates[lastAddedCursorIndex] = CursorMoveCommands.moveTo(context, states[lastAddedCursorIndex], true, args.position, args.viewPosition);\n cursors.context.model.pushStackElement();\n cursors.setStates(args.source, 3 /* Explicit */, newStates);\n };\n return class_5;\n }(CoreEditorCommand)));\n var HomeCommand = /** @class */ (function (_super) {\n __extends(HomeCommand, _super);\n function HomeCommand(opts) {\n var _this = _super.call(this, opts) || this;\n _this._inSelectionMode = opts.inSelectionMode;\n return _this;\n }\n HomeCommand.prototype.runCoreEditorCommand = function (cursors, args) {\n cursors.context.model.pushStackElement();\n cursors.setStates(args.source, 3 /* Explicit */, CursorMoveCommands.moveToBeginningOfLine(cursors.context, cursors.getAll(), this._inSelectionMode));\n cursors.reveal(true, 0 /* Primary */, 0 /* Smooth */);\n };\n return HomeCommand;\n }(CoreEditorCommand));\n CoreNavigationCommands.CursorHome = registerEditorCommand(new HomeCommand({\n inSelectionMode: false,\n id: 'cursorHome',\n precondition: null,\n kbOpts: {\n weight: CORE_WEIGHT,\n kbExpr: EditorContextKeys.textInputFocus,\n primary: 14 /* Home */,\n mac: { primary: 14 /* Home */, secondary: [2048 /* CtrlCmd */ | 15 /* LeftArrow */] }\n }\n }));\n CoreNavigationCommands.CursorHomeSelect = registerEditorCommand(new HomeCommand({\n inSelectionMode: true,\n id: 'cursorHomeSelect',\n precondition: null,\n kbOpts: {\n weight: CORE_WEIGHT,\n kbExpr: EditorContextKeys.textInputFocus,\n primary: 1024 /* Shift */ | 14 /* Home */,\n mac: { primary: 1024 /* Shift */ | 14 /* Home */, secondary: [2048 /* CtrlCmd */ | 1024 /* Shift */ | 15 /* LeftArrow */] }\n }\n }));\n CoreNavigationCommands.CursorLineStart = registerEditorCommand(new /** @class */ (function (_super) {\n __extends(class_6, _super);\n function class_6() {\n return _super.call(this, {\n id: 'cursorLineStart',\n precondition: null,\n kbOpts: {\n weight: CORE_WEIGHT,\n kbExpr: EditorContextKeys.textInputFocus,\n primary: 0,\n mac: { primary: 256 /* WinCtrl */ | 31 /* KEY_A */ }\n }\n }) || this;\n }\n class_6.prototype.runCoreEditorCommand = function (cursors, args) {\n cursors.context.model.pushStackElement();\n cursors.setStates(args.source, 3 /* Explicit */, this._exec(cursors.context, cursors.getAll()));\n cursors.reveal(true, 0 /* Primary */, 0 /* Smooth */);\n };\n class_6.prototype._exec = function (context, cursors) {\n var result = [];\n for (var i = 0, len = cursors.length; i < len; i++) {\n var cursor = cursors[i];\n var lineNumber = cursor.modelState.position.lineNumber;\n result[i] = CursorState.fromModelState(cursor.modelState.move(false, lineNumber, 1, 0));\n }\n return result;\n };\n return class_6;\n }(CoreEditorCommand)));\n var EndCommand = /** @class */ (function (_super) {\n __extends(EndCommand, _super);\n function EndCommand(opts) {\n var _this = _super.call(this, opts) || this;\n _this._inSelectionMode = opts.inSelectionMode;\n return _this;\n }\n EndCommand.prototype.runCoreEditorCommand = function (cursors, args) {\n cursors.context.model.pushStackElement();\n cursors.setStates(args.source, 3 /* Explicit */, CursorMoveCommands.moveToEndOfLine(cursors.context, cursors.getAll(), this._inSelectionMode));\n cursors.reveal(true, 0 /* Primary */, 0 /* Smooth */);\n };\n return EndCommand;\n }(CoreEditorCommand));\n CoreNavigationCommands.CursorEnd = registerEditorCommand(new EndCommand({\n inSelectionMode: false,\n id: 'cursorEnd',\n precondition: null,\n kbOpts: {\n weight: CORE_WEIGHT,\n kbExpr: EditorContextKeys.textInputFocus,\n primary: 13 /* End */,\n mac: { primary: 13 /* End */, secondary: [2048 /* CtrlCmd */ | 17 /* RightArrow */] }\n }\n }));\n CoreNavigationCommands.CursorEndSelect = registerEditorCommand(new EndCommand({\n inSelectionMode: true,\n id: 'cursorEndSelect',\n precondition: null,\n kbOpts: {\n weight: CORE_WEIGHT,\n kbExpr: EditorContextKeys.textInputFocus,\n primary: 1024 /* Shift */ | 13 /* End */,\n mac: { primary: 1024 /* Shift */ | 13 /* End */, secondary: [2048 /* CtrlCmd */ | 1024 /* Shift */ | 17 /* RightArrow */] }\n }\n }));\n CoreNavigationCommands.CursorLineEnd = registerEditorCommand(new /** @class */ (function (_super) {\n __extends(class_7, _super);\n function class_7() {\n return _super.call(this, {\n id: 'cursorLineEnd',\n precondition: null,\n kbOpts: {\n weight: CORE_WEIGHT,\n kbExpr: EditorContextKeys.textInputFocus,\n primary: 0,\n mac: { primary: 256 /* WinCtrl */ | 35 /* KEY_E */ }\n }\n }) || this;\n }\n class_7.prototype.runCoreEditorCommand = function (cursors, args) {\n cursors.context.model.pushStackElement();\n cursors.setStates(args.source, 3 /* Explicit */, this._exec(cursors.context, cursors.getAll()));\n cursors.reveal(true, 0 /* Primary */, 0 /* Smooth */);\n };\n class_7.prototype._exec = function (context, cursors) {\n var result = [];\n for (var i = 0, len = cursors.length; i < len; i++) {\n var cursor = cursors[i];\n var lineNumber = cursor.modelState.position.lineNumber;\n var maxColumn = context.model.getLineMaxColumn(lineNumber);\n result[i] = CursorState.fromModelState(cursor.modelState.move(false, lineNumber, maxColumn, 0));\n }\n return result;\n };\n return class_7;\n }(CoreEditorCommand)));\n var TopCommand = /** @class */ (function (_super) {\n __extends(TopCommand, _super);\n function TopCommand(opts) {\n var _this = _super.call(this, opts) || this;\n _this._inSelectionMode = opts.inSelectionMode;\n return _this;\n }\n TopCommand.prototype.runCoreEditorCommand = function (cursors, args) {\n cursors.context.model.pushStackElement();\n cursors.setStates(args.source, 3 /* Explicit */, CursorMoveCommands.moveToBeginningOfBuffer(cursors.context, cursors.getAll(), this._inSelectionMode));\n cursors.reveal(true, 0 /* Primary */, 0 /* Smooth */);\n };\n return TopCommand;\n }(CoreEditorCommand));\n CoreNavigationCommands.CursorTop = registerEditorCommand(new TopCommand({\n inSelectionMode: false,\n id: 'cursorTop',\n precondition: null,\n kbOpts: {\n weight: CORE_WEIGHT,\n kbExpr: EditorContextKeys.textInputFocus,\n primary: 2048 /* CtrlCmd */ | 14 /* Home */,\n mac: { primary: 2048 /* CtrlCmd */ | 16 /* UpArrow */ }\n }\n }));\n CoreNavigationCommands.CursorTopSelect = registerEditorCommand(new TopCommand({\n inSelectionMode: true,\n id: 'cursorTopSelect',\n precondition: null,\n kbOpts: {\n weight: CORE_WEIGHT,\n kbExpr: EditorContextKeys.textInputFocus,\n primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 14 /* Home */,\n mac: { primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 16 /* UpArrow */ }\n }\n }));\n var BottomCommand = /** @class */ (function (_super) {\n __extends(BottomCommand, _super);\n function BottomCommand(opts) {\n var _this = _super.call(this, opts) || this;\n _this._inSelectionMode = opts.inSelectionMode;\n return _this;\n }\n BottomCommand.prototype.runCoreEditorCommand = function (cursors, args) {\n cursors.context.model.pushStackElement();\n cursors.setStates(args.source, 3 /* Explicit */, CursorMoveCommands.moveToEndOfBuffer(cursors.context, cursors.getAll(), this._inSelectionMode));\n cursors.reveal(true, 0 /* Primary */, 0 /* Smooth */);\n };\n return BottomCommand;\n }(CoreEditorCommand));\n CoreNavigationCommands.CursorBottom = registerEditorCommand(new BottomCommand({\n inSelectionMode: false,\n id: 'cursorBottom',\n precondition: null,\n kbOpts: {\n weight: CORE_WEIGHT,\n kbExpr: EditorContextKeys.textInputFocus,\n primary: 2048 /* CtrlCmd */ | 13 /* End */,\n mac: { primary: 2048 /* CtrlCmd */ | 18 /* DownArrow */ }\n }\n }));\n CoreNavigationCommands.CursorBottomSelect = registerEditorCommand(new BottomCommand({\n inSelectionMode: true,\n id: 'cursorBottomSelect',\n precondition: null,\n kbOpts: {\n weight: CORE_WEIGHT,\n kbExpr: EditorContextKeys.textInputFocus,\n primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 13 /* End */,\n mac: { primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 18 /* DownArrow */ }\n }\n }));\n var EditorScrollImpl = /** @class */ (function (_super) {\n __extends(EditorScrollImpl, _super);\n function EditorScrollImpl() {\n return _super.call(this, {\n id: 'editorScroll',\n precondition: null,\n description: EditorScroll_.description\n }) || this;\n }\n EditorScrollImpl.prototype.runCoreEditorCommand = function (cursors, args) {\n var parsed = EditorScroll_.parse(args);\n if (!parsed) {\n // illegal arguments\n return;\n }\n this._runEditorScroll(cursors, args.source, parsed);\n };\n EditorScrollImpl.prototype._runEditorScroll = function (cursors, source, args) {\n var desiredScrollTop = this._computeDesiredScrollTop(cursors.context, args);\n if (args.revealCursor) {\n // must ensure cursor is in new visible range\n var desiredVisibleViewRange = cursors.context.getCompletelyVisibleViewRangeAtScrollTop(desiredScrollTop);\n cursors.setStates(source, 3 /* Explicit */, [\n CursorMoveCommands.findPositionInViewportIfOutside(cursors.context, cursors.getPrimaryCursor(), desiredVisibleViewRange, args.select)\n ]);\n }\n cursors.scrollTo(desiredScrollTop);\n };\n EditorScrollImpl.prototype._computeDesiredScrollTop = function (context, args) {\n if (args.unit === 1 /* Line */) {\n // scrolling by model lines\n var visibleModelRange = context.getCompletelyVisibleModelRange();\n var desiredTopModelLineNumber = void 0;\n if (args.direction === 1 /* Up */) {\n // must go x model lines up\n desiredTopModelLineNumber = Math.max(1, visibleModelRange.startLineNumber - args.value);\n }\n else {\n // must go x model lines down\n desiredTopModelLineNumber = Math.min(context.model.getLineCount(), visibleModelRange.startLineNumber + args.value);\n }\n var desiredTopViewPosition = context.convertModelPositionToViewPosition(new Position(desiredTopModelLineNumber, 1));\n return context.getVerticalOffsetForViewLine(desiredTopViewPosition.lineNumber);\n }\n var noOfLines;\n if (args.unit === 3 /* Page */) {\n noOfLines = context.config.pageSize * args.value;\n }\n else if (args.unit === 4 /* HalfPage */) {\n noOfLines = Math.round(context.config.pageSize / 2) * args.value;\n }\n else {\n noOfLines = args.value;\n }\n var deltaLines = (args.direction === 1 /* Up */ ? -1 : 1) * noOfLines;\n return context.getCurrentScrollTop() + deltaLines * context.config.lineHeight;\n };\n return EditorScrollImpl;\n }(CoreEditorCommand));\n CoreNavigationCommands.EditorScrollImpl = EditorScrollImpl;\n CoreNavigationCommands.EditorScroll = registerEditorCommand(new EditorScrollImpl());\n CoreNavigationCommands.ScrollLineUp = registerEditorCommand(new /** @class */ (function (_super) {\n __extends(class_8, _super);\n function class_8() {\n return _super.call(this, {\n id: 'scrollLineUp',\n precondition: null,\n kbOpts: {\n weight: CORE_WEIGHT,\n kbExpr: EditorContextKeys.textInputFocus,\n primary: 2048 /* CtrlCmd */ | 16 /* UpArrow */,\n mac: { primary: 256 /* WinCtrl */ | 11 /* PageUp */ }\n }\n }) || this;\n }\n class_8.prototype.runCoreEditorCommand = function (cursors, args) {\n CoreNavigationCommands.EditorScroll._runEditorScroll(cursors, args.source, {\n direction: 1 /* Up */,\n unit: 2 /* WrappedLine */,\n value: 1,\n revealCursor: false,\n select: false\n });\n };\n return class_8;\n }(CoreEditorCommand)));\n CoreNavigationCommands.ScrollPageUp = registerEditorCommand(new /** @class */ (function (_super) {\n __extends(class_9, _super);\n function class_9() {\n return _super.call(this, {\n id: 'scrollPageUp',\n precondition: null,\n kbOpts: {\n weight: CORE_WEIGHT,\n kbExpr: EditorContextKeys.textInputFocus,\n primary: 2048 /* CtrlCmd */ | 11 /* PageUp */,\n win: { primary: 512 /* Alt */ | 11 /* PageUp */ },\n linux: { primary: 512 /* Alt */ | 11 /* PageUp */ }\n }\n }) || this;\n }\n class_9.prototype.runCoreEditorCommand = function (cursors, args) {\n CoreNavigationCommands.EditorScroll._runEditorScroll(cursors, args.source, {\n direction: 1 /* Up */,\n unit: 3 /* Page */,\n value: 1,\n revealCursor: false,\n select: false\n });\n };\n return class_9;\n }(CoreEditorCommand)));\n CoreNavigationCommands.ScrollLineDown = registerEditorCommand(new /** @class */ (function (_super) {\n __extends(class_10, _super);\n function class_10() {\n return _super.call(this, {\n id: 'scrollLineDown',\n precondition: null,\n kbOpts: {\n weight: CORE_WEIGHT,\n kbExpr: EditorContextKeys.textInputFocus,\n primary: 2048 /* CtrlCmd */ | 18 /* DownArrow */,\n mac: { primary: 256 /* WinCtrl */ | 12 /* PageDown */ }\n }\n }) || this;\n }\n class_10.prototype.runCoreEditorCommand = function (cursors, args) {\n CoreNavigationCommands.EditorScroll._runEditorScroll(cursors, args.source, {\n direction: 2 /* Down */,\n unit: 2 /* WrappedLine */,\n value: 1,\n revealCursor: false,\n select: false\n });\n };\n return class_10;\n }(CoreEditorCommand)));\n CoreNavigationCommands.ScrollPageDown = registerEditorCommand(new /** @class */ (function (_super) {\n __extends(class_11, _super);\n function class_11() {\n return _super.call(this, {\n id: 'scrollPageDown',\n precondition: null,\n kbOpts: {\n weight: CORE_WEIGHT,\n kbExpr: EditorContextKeys.textInputFocus,\n primary: 2048 /* CtrlCmd */ | 12 /* PageDown */,\n win: { primary: 512 /* Alt */ | 12 /* PageDown */ },\n linux: { primary: 512 /* Alt */ | 12 /* PageDown */ }\n }\n }) || this;\n }\n class_11.prototype.runCoreEditorCommand = function (cursors, args) {\n CoreNavigationCommands.EditorScroll._runEditorScroll(cursors, args.source, {\n direction: 2 /* Down */,\n unit: 3 /* Page */,\n value: 1,\n revealCursor: false,\n select: false\n });\n };\n return class_11;\n }(CoreEditorCommand)));\n var WordCommand = /** @class */ (function (_super) {\n __extends(WordCommand, _super);\n function WordCommand(opts) {\n var _this = _super.call(this, opts) || this;\n _this._inSelectionMode = opts.inSelectionMode;\n return _this;\n }\n WordCommand.prototype.runCoreEditorCommand = function (cursors, args) {\n cursors.context.model.pushStackElement();\n cursors.setStates(args.source, 3 /* Explicit */, [\n CursorMoveCommands.word(cursors.context, cursors.getPrimaryCursor(), this._inSelectionMode, args.position)\n ]);\n cursors.reveal(true, 0 /* Primary */, 0 /* Smooth */);\n };\n return WordCommand;\n }(CoreEditorCommand));\n CoreNavigationCommands.WordSelect = registerEditorCommand(new WordCommand({\n inSelectionMode: false,\n id: '_wordSelect',\n precondition: null\n }));\n CoreNavigationCommands.WordSelectDrag = registerEditorCommand(new WordCommand({\n inSelectionMode: true,\n id: '_wordSelectDrag',\n precondition: null\n }));\n CoreNavigationCommands.LastCursorWordSelect = registerEditorCommand(new /** @class */ (function (_super) {\n __extends(class_12, _super);\n function class_12() {\n return _super.call(this, {\n id: 'lastCursorWordSelect',\n precondition: null\n }) || this;\n }\n class_12.prototype.runCoreEditorCommand = function (cursors, args) {\n var context = cursors.context;\n var lastAddedCursorIndex = cursors.getLastAddedCursorIndex();\n var states = cursors.getAll();\n var newStates = states.slice(0);\n var lastAddedState = states[lastAddedCursorIndex];\n newStates[lastAddedCursorIndex] = CursorMoveCommands.word(context, lastAddedState, lastAddedState.modelState.hasSelection(), args.position);\n context.model.pushStackElement();\n cursors.setStates(args.source, 3 /* Explicit */, newStates);\n };\n return class_12;\n }(CoreEditorCommand)));\n var LineCommand = /** @class */ (function (_super) {\n __extends(LineCommand, _super);\n function LineCommand(opts) {\n var _this = _super.call(this, opts) || this;\n _this._inSelectionMode = opts.inSelectionMode;\n return _this;\n }\n LineCommand.prototype.runCoreEditorCommand = function (cursors, args) {\n cursors.context.model.pushStackElement();\n cursors.setStates(args.source, 3 /* Explicit */, [\n CursorMoveCommands.line(cursors.context, cursors.getPrimaryCursor(), this._inSelectionMode, args.position, args.viewPosition)\n ]);\n cursors.reveal(false, 0 /* Primary */, 0 /* Smooth */);\n };\n return LineCommand;\n }(CoreEditorCommand));\n CoreNavigationCommands.LineSelect = registerEditorCommand(new LineCommand({\n inSelectionMode: false,\n id: '_lineSelect',\n precondition: null\n }));\n CoreNavigationCommands.LineSelectDrag = registerEditorCommand(new LineCommand({\n inSelectionMode: true,\n id: '_lineSelectDrag',\n precondition: null\n }));\n var LastCursorLineCommand = /** @class */ (function (_super) {\n __extends(LastCursorLineCommand, _super);\n function LastCursorLineCommand(opts) {\n var _this = _super.call(this, opts) || this;\n _this._inSelectionMode = opts.inSelectionMode;\n return _this;\n }\n LastCursorLineCommand.prototype.runCoreEditorCommand = function (cursors, args) {\n var lastAddedCursorIndex = cursors.getLastAddedCursorIndex();\n var states = cursors.getAll();\n var newStates = states.slice(0);\n newStates[lastAddedCursorIndex] = CursorMoveCommands.line(cursors.context, states[lastAddedCursorIndex], this._inSelectionMode, args.position, args.viewPosition);\n cursors.context.model.pushStackElement();\n cursors.setStates(args.source, 3 /* Explicit */, newStates);\n };\n return LastCursorLineCommand;\n }(CoreEditorCommand));\n CoreNavigationCommands.LastCursorLineSelect = registerEditorCommand(new LastCursorLineCommand({\n inSelectionMode: false,\n id: 'lastCursorLineSelect',\n precondition: null\n }));\n CoreNavigationCommands.LastCursorLineSelectDrag = registerEditorCommand(new LastCursorLineCommand({\n inSelectionMode: true,\n id: 'lastCursorLineSelectDrag',\n precondition: null\n }));\n CoreNavigationCommands.ExpandLineSelection = registerEditorCommand(new /** @class */ (function (_super) {\n __extends(class_13, _super);\n function class_13() {\n return _super.call(this, {\n id: 'expandLineSelection',\n precondition: null,\n kbOpts: {\n weight: CORE_WEIGHT,\n kbExpr: EditorContextKeys.textInputFocus,\n primary: 2048 /* CtrlCmd */ | 42 /* KEY_L */\n }\n }) || this;\n }\n class_13.prototype.runCoreEditorCommand = function (cursors, args) {\n cursors.context.model.pushStackElement();\n cursors.setStates(args.source, 3 /* Explicit */, CursorMoveCommands.expandLineSelection(cursors.context, cursors.getAll()));\n cursors.reveal(true, 0 /* Primary */, 0 /* Smooth */);\n };\n return class_13;\n }(CoreEditorCommand)));\n CoreNavigationCommands.CancelSelection = registerEditorCommand(new /** @class */ (function (_super) {\n __extends(class_14, _super);\n function class_14() {\n return _super.call(this, {\n id: 'cancelSelection',\n precondition: EditorContextKeys.hasNonEmptySelection,\n kbOpts: {\n weight: CORE_WEIGHT,\n kbExpr: EditorContextKeys.textInputFocus,\n primary: 9 /* Escape */,\n secondary: [1024 /* Shift */ | 9 /* Escape */]\n }\n }) || this;\n }\n class_14.prototype.runCoreEditorCommand = function (cursors, args) {\n cursors.context.model.pushStackElement();\n cursors.setStates(args.source, 3 /* Explicit */, [\n CursorMoveCommands.cancelSelection(cursors.context, cursors.getPrimaryCursor())\n ]);\n cursors.reveal(true, 0 /* Primary */, 0 /* Smooth */);\n };\n return class_14;\n }(CoreEditorCommand)));\n CoreNavigationCommands.RemoveSecondaryCursors = registerEditorCommand(new /** @class */ (function (_super) {\n __extends(class_15, _super);\n function class_15() {\n return _super.call(this, {\n id: 'removeSecondaryCursors',\n precondition: EditorContextKeys.hasMultipleSelections,\n kbOpts: {\n weight: CORE_WEIGHT + 1,\n kbExpr: EditorContextKeys.textInputFocus,\n primary: 9 /* Escape */,\n secondary: [1024 /* Shift */ | 9 /* Escape */]\n }\n }) || this;\n }\n class_15.prototype.runCoreEditorCommand = function (cursors, args) {\n cursors.context.model.pushStackElement();\n cursors.setStates(args.source, 3 /* Explicit */, [\n cursors.getPrimaryCursor()\n ]);\n cursors.reveal(true, 0 /* Primary */, 0 /* Smooth */);\n };\n return class_15;\n }(CoreEditorCommand)));\n CoreNavigationCommands.RevealLine = registerEditorCommand(new /** @class */ (function (_super) {\n __extends(class_16, _super);\n function class_16() {\n return _super.call(this, {\n id: 'revealLine',\n precondition: null,\n description: RevealLine_.description\n }) || this;\n }\n class_16.prototype.runCoreEditorCommand = function (cursors, args) {\n var revealLineArg = args;\n var lineNumber = (revealLineArg.lineNumber || 0) + 1;\n if (lineNumber < 1) {\n lineNumber = 1;\n }\n var lineCount = cursors.context.model.getLineCount();\n if (lineNumber > lineCount) {\n lineNumber = lineCount;\n }\n var range = new Range(lineNumber, 1, lineNumber, cursors.context.model.getLineMaxColumn(lineNumber));\n var revealAt = 0 /* Simple */;\n if (revealLineArg.at) {\n switch (revealLineArg.at) {\n case RevealLine_.RawAtArgument.Top:\n revealAt = 3 /* Top */;\n break;\n case RevealLine_.RawAtArgument.Center:\n revealAt = 1 /* Center */;\n break;\n case RevealLine_.RawAtArgument.Bottom:\n revealAt = 4 /* Bottom */;\n break;\n default:\n break;\n }\n }\n var viewRange = cursors.context.convertModelRangeToViewRange(range);\n cursors.revealRange(false, viewRange, revealAt, 0 /* Smooth */);\n };\n return class_16;\n }(CoreEditorCommand)));\n CoreNavigationCommands.SelectAll = registerEditorCommand(new /** @class */ (function (_super) {\n __extends(class_17, _super);\n function class_17() {\n return _super.call(this, {\n id: 'selectAll',\n precondition: null\n }) || this;\n }\n class_17.prototype.runCoreEditorCommand = function (cursors, args) {\n cursors.context.model.pushStackElement();\n cursors.setStates(args.source, 3 /* Explicit */, [\n CursorMoveCommands.selectAll(cursors.context, cursors.getPrimaryCursor())\n ]);\n };\n return class_17;\n }(CoreEditorCommand)));\n CoreNavigationCommands.SetSelection = registerEditorCommand(new /** @class */ (function (_super) {\n __extends(class_18, _super);\n function class_18() {\n return _super.call(this, {\n id: 'setSelection',\n precondition: null\n }) || this;\n }\n class_18.prototype.runCoreEditorCommand = function (cursors, args) {\n cursors.context.model.pushStackElement();\n cursors.setStates(args.source, 3 /* Explicit */, [\n CursorState.fromModelSelection(args.selection)\n ]);\n };\n return class_18;\n }(CoreEditorCommand)));\n})(CoreNavigationCommands || (CoreNavigationCommands = {}));\nexport var CoreEditingCommands;\n(function (CoreEditingCommands) {\n var CoreEditingCommand = /** @class */ (function (_super) {\n __extends(CoreEditingCommand, _super);\n function CoreEditingCommand() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n CoreEditingCommand.prototype.runEditorCommand = function (accessor, editor, args) {\n var cursors = editor._getCursors();\n if (!cursors) {\n // the editor has no view => has no cursors\n return;\n }\n this.runCoreEditingCommand(editor, cursors, args || {});\n };\n return CoreEditingCommand;\n }(EditorCommand));\n CoreEditingCommands.CoreEditingCommand = CoreEditingCommand;\n CoreEditingCommands.LineBreakInsert = registerEditorCommand(new /** @class */ (function (_super) {\n __extends(class_19, _super);\n function class_19() {\n return _super.call(this, {\n id: 'lineBreakInsert',\n precondition: EditorContextKeys.writable,\n kbOpts: {\n weight: CORE_WEIGHT,\n kbExpr: EditorContextKeys.textInputFocus,\n primary: 0,\n mac: { primary: 256 /* WinCtrl */ | 45 /* KEY_O */ }\n }\n }) || this;\n }\n class_19.prototype.runCoreEditingCommand = function (editor, cursors, args) {\n editor.pushUndoStop();\n editor.executeCommands(this.id, TypeOperations.lineBreakInsert(cursors.context.config, cursors.context.model, cursors.getAll().map(function (s) { return s.modelState.selection; })));\n };\n return class_19;\n }(CoreEditingCommand)));\n CoreEditingCommands.Outdent = registerEditorCommand(new /** @class */ (function (_super) {\n __extends(class_20, _super);\n function class_20() {\n return _super.call(this, {\n id: 'outdent',\n precondition: EditorContextKeys.writable,\n kbOpts: {\n weight: CORE_WEIGHT,\n kbExpr: ContextKeyExpr.and(EditorContextKeys.editorTextFocus, EditorContextKeys.tabDoesNotMoveFocus),\n primary: 1024 /* Shift */ | 2 /* Tab */\n }\n }) || this;\n }\n class_20.prototype.runCoreEditingCommand = function (editor, cursors, args) {\n editor.pushUndoStop();\n editor.executeCommands(this.id, TypeOperations.outdent(cursors.context.config, cursors.context.model, cursors.getAll().map(function (s) { return s.modelState.selection; })));\n editor.pushUndoStop();\n };\n return class_20;\n }(CoreEditingCommand)));\n CoreEditingCommands.Tab = registerEditorCommand(new /** @class */ (function (_super) {\n __extends(class_21, _super);\n function class_21() {\n return _super.call(this, {\n id: 'tab',\n precondition: EditorContextKeys.writable,\n kbOpts: {\n weight: CORE_WEIGHT,\n kbExpr: ContextKeyExpr.and(EditorContextKeys.editorTextFocus, EditorContextKeys.tabDoesNotMoveFocus),\n primary: 2 /* Tab */\n }\n }) || this;\n }\n class_21.prototype.runCoreEditingCommand = function (editor, cursors, args) {\n editor.pushUndoStop();\n editor.executeCommands(this.id, TypeOperations.tab(cursors.context.config, cursors.context.model, cursors.getAll().map(function (s) { return s.modelState.selection; })));\n editor.pushUndoStop();\n };\n return class_21;\n }(CoreEditingCommand)));\n CoreEditingCommands.DeleteLeft = registerEditorCommand(new /** @class */ (function (_super) {\n __extends(class_22, _super);\n function class_22() {\n return _super.call(this, {\n id: 'deleteLeft',\n precondition: EditorContextKeys.writable,\n kbOpts: {\n weight: CORE_WEIGHT,\n kbExpr: EditorContextKeys.textInputFocus,\n primary: 1 /* Backspace */,\n secondary: [1024 /* Shift */ | 1 /* Backspace */],\n mac: { primary: 1 /* Backspace */, secondary: [1024 /* Shift */ | 1 /* Backspace */, 256 /* WinCtrl */ | 38 /* KEY_H */, 256 /* WinCtrl */ | 1 /* Backspace */] }\n }\n }) || this;\n }\n class_22.prototype.runCoreEditingCommand = function (editor, cursors, args) {\n var _a = DeleteOperations.deleteLeft(cursors.getPrevEditOperationType(), cursors.context.config, cursors.context.model, cursors.getAll().map(function (s) { return s.modelState.selection; })), shouldPushStackElementBefore = _a[0], commands = _a[1];\n if (shouldPushStackElementBefore) {\n editor.pushUndoStop();\n }\n editor.executeCommands(this.id, commands);\n cursors.setPrevEditOperationType(2 /* DeletingLeft */);\n };\n return class_22;\n }(CoreEditingCommand)));\n CoreEditingCommands.DeleteRight = registerEditorCommand(new /** @class */ (function (_super) {\n __extends(class_23, _super);\n function class_23() {\n return _super.call(this, {\n id: 'deleteRight',\n precondition: EditorContextKeys.writable,\n kbOpts: {\n weight: CORE_WEIGHT,\n kbExpr: EditorContextKeys.textInputFocus,\n primary: 20 /* Delete */,\n mac: { primary: 20 /* Delete */, secondary: [256 /* WinCtrl */ | 34 /* KEY_D */, 256 /* WinCtrl */ | 20 /* Delete */] }\n }\n }) || this;\n }\n class_23.prototype.runCoreEditingCommand = function (editor, cursors, args) {\n var _a = DeleteOperations.deleteRight(cursors.getPrevEditOperationType(), cursors.context.config, cursors.context.model, cursors.getAll().map(function (s) { return s.modelState.selection; })), shouldPushStackElementBefore = _a[0], commands = _a[1];\n if (shouldPushStackElementBefore) {\n editor.pushUndoStop();\n }\n editor.executeCommands(this.id, commands);\n cursors.setPrevEditOperationType(3 /* DeletingRight */);\n };\n return class_23;\n }(CoreEditingCommand)));\n})(CoreEditingCommands || (CoreEditingCommands = {}));\nfunction registerCommand(command) {\n command.register();\n}\n/**\n * A command that will:\n * 1. invoke a command on the focused editor.\n * 2. otherwise, invoke a browser built-in command on the `activeElement`.\n * 3. otherwise, invoke a command on the workbench active editor.\n */\nvar EditorOrNativeTextInputCommand = /** @class */ (function (_super) {\n __extends(EditorOrNativeTextInputCommand, _super);\n function EditorOrNativeTextInputCommand(opts) {\n var _this = _super.call(this, opts) || this;\n _this._editorHandler = opts.editorHandler;\n _this._inputHandler = opts.inputHandler;\n return _this;\n }\n EditorOrNativeTextInputCommand.prototype.runCommand = function (accessor, args) {\n var focusedEditor = accessor.get(ICodeEditorService).getFocusedCodeEditor();\n // Only if editor text focus (i.e. not if editor has widget focus).\n if (focusedEditor && focusedEditor.hasTextFocus()) {\n return this._runEditorHandler(accessor, focusedEditor, args);\n }\n // Ignore this action when user is focused on an element that allows for entering text\n var activeElement = document.activeElement;\n if (activeElement && ['input', 'textarea'].indexOf(activeElement.tagName.toLowerCase()) >= 0) {\n document.execCommand(this._inputHandler);\n return;\n }\n // Redirecting to active editor\n var activeEditor = accessor.get(ICodeEditorService).getActiveCodeEditor();\n if (activeEditor) {\n activeEditor.focus();\n return this._runEditorHandler(accessor, activeEditor, args);\n }\n };\n EditorOrNativeTextInputCommand.prototype._runEditorHandler = function (accessor, editor, args) {\n var HANDLER = this._editorHandler;\n if (typeof HANDLER === 'string') {\n editor.trigger('keyboard', HANDLER, args);\n }\n else {\n args = args || {};\n args.source = 'keyboard';\n HANDLER.runEditorCommand(accessor, editor, args);\n }\n };\n return EditorOrNativeTextInputCommand;\n}(Command));\n/**\n * A command that will invoke a command on the focused editor.\n */\nvar EditorHandlerCommand = /** @class */ (function (_super) {\n __extends(EditorHandlerCommand, _super);\n function EditorHandlerCommand(id, handlerId, description) {\n var _this = _super.call(this, {\n id: id,\n precondition: null,\n description: description\n }) || this;\n _this._handlerId = handlerId;\n return _this;\n }\n EditorHandlerCommand.prototype.runCommand = function (accessor, args) {\n var editor = accessor.get(ICodeEditorService).getFocusedCodeEditor();\n if (!editor) {\n return;\n }\n editor.trigger('keyboard', this._handlerId, args);\n };\n return EditorHandlerCommand;\n}(Command));\nregisterCommand(new EditorOrNativeTextInputCommand({\n editorHandler: CoreNavigationCommands.SelectAll,\n inputHandler: 'selectAll',\n id: 'editor.action.selectAll',\n precondition: EditorContextKeys.textInputFocus,\n kbOpts: {\n weight: CORE_WEIGHT,\n kbExpr: null,\n primary: 2048 /* CtrlCmd */ | 31 /* KEY_A */\n },\n menubarOpts: {\n menuId: 22 /* MenubarSelectionMenu */,\n group: '1_basic',\n title: nls.localize({ key: 'miSelectAll', comment: ['&& denotes a mnemonic'] }, \"&&Select All\"),\n order: 1\n }\n}));\nregisterCommand(new EditorOrNativeTextInputCommand({\n editorHandler: Handler.Undo,\n inputHandler: 'undo',\n id: Handler.Undo,\n precondition: EditorContextKeys.writable,\n kbOpts: {\n weight: CORE_WEIGHT,\n kbExpr: EditorContextKeys.textInputFocus,\n primary: 2048 /* CtrlCmd */ | 56 /* KEY_Z */\n },\n menubarOpts: {\n menuId: 14 /* MenubarEditMenu */,\n group: '1_do',\n title: nls.localize({ key: 'miUndo', comment: ['&& denotes a mnemonic'] }, \"&&Undo\"),\n order: 1\n }\n}));\nregisterCommand(new EditorHandlerCommand('default:' + Handler.Undo, Handler.Undo));\nregisterCommand(new EditorOrNativeTextInputCommand({\n editorHandler: Handler.Redo,\n inputHandler: 'redo',\n id: Handler.Redo,\n precondition: EditorContextKeys.writable,\n kbOpts: {\n weight: CORE_WEIGHT,\n kbExpr: EditorContextKeys.textInputFocus,\n primary: 2048 /* CtrlCmd */ | 55 /* KEY_Y */,\n secondary: [2048 /* CtrlCmd */ | 1024 /* Shift */ | 56 /* KEY_Z */],\n mac: { primary: 2048 /* CtrlCmd */ | 1024 /* Shift */ | 56 /* KEY_Z */ }\n },\n menubarOpts: {\n menuId: 14 /* MenubarEditMenu */,\n group: '1_do',\n title: nls.localize({ key: 'miRedo', comment: ['&& denotes a mnemonic'] }, \"&&Redo\"),\n order: 2\n }\n}));\nregisterCommand(new EditorHandlerCommand('default:' + Handler.Redo, Handler.Redo));\nfunction registerOverwritableCommand(handlerId, description) {\n registerCommand(new EditorHandlerCommand('default:' + handlerId, handlerId));\n registerCommand(new EditorHandlerCommand(handlerId, handlerId, description));\n}\nregisterOverwritableCommand(Handler.Type, {\n description: \"Type\",\n args: [{\n name: 'args',\n schema: {\n 'type': 'object',\n 'required': ['text'],\n 'properties': {\n 'text': {\n 'type': 'string'\n }\n },\n }\n }]\n});\nregisterOverwritableCommand(Handler.ReplacePreviousChar);\nregisterOverwritableCommand(Handler.CompositionStart);\nregisterOverwritableCommand(Handler.CompositionEnd);\nregisterOverwritableCommand(Handler.Paste);\nregisterOverwritableCommand(Handler.Cut);\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport { CoreNavigationCommands } from '../controller/coreCommands.js';\nimport { Position } from '../../common/core/position.js';\nvar ViewController = /** @class */ (function () {\n function ViewController(configuration, viewModel, outgoingEvents, commandDelegate) {\n this.configuration = configuration;\n this.viewModel = viewModel;\n this.outgoingEvents = outgoingEvents;\n this.commandDelegate = commandDelegate;\n }\n ViewController.prototype._execMouseCommand = function (editorCommand, args) {\n args.source = 'mouse';\n this.commandDelegate.executeEditorCommand(editorCommand, args);\n };\n ViewController.prototype.paste = function (source, text, pasteOnNewLine, multicursorText) {\n this.commandDelegate.paste(source, text, pasteOnNewLine, multicursorText);\n };\n ViewController.prototype.type = function (source, text) {\n this.commandDelegate.type(source, text);\n };\n ViewController.prototype.replacePreviousChar = function (source, text, replaceCharCnt) {\n this.commandDelegate.replacePreviousChar(source, text, replaceCharCnt);\n };\n ViewController.prototype.compositionStart = function (source) {\n this.commandDelegate.compositionStart(source);\n };\n ViewController.prototype.compositionEnd = function (source) {\n this.commandDelegate.compositionEnd(source);\n };\n ViewController.prototype.cut = function (source) {\n this.commandDelegate.cut(source);\n };\n ViewController.prototype.setSelection = function (source, modelSelection) {\n this.commandDelegate.executeEditorCommand(CoreNavigationCommands.SetSelection, {\n source: source,\n selection: modelSelection\n });\n };\n ViewController.prototype._validateViewColumn = function (viewPosition) {\n var minColumn = this.viewModel.getLineMinColumn(viewPosition.lineNumber);\n if (viewPosition.column < minColumn) {\n return new Position(viewPosition.lineNumber, minColumn);\n }\n return viewPosition;\n };\n ViewController.prototype._hasMulticursorModifier = function (data) {\n switch (this.configuration.editor.multiCursorModifier) {\n case 'altKey':\n return data.altKey;\n case 'ctrlKey':\n return data.ctrlKey;\n case 'metaKey':\n return data.metaKey;\n }\n return false;\n };\n ViewController.prototype._hasNonMulticursorModifier = function (data) {\n switch (this.configuration.editor.multiCursorModifier) {\n case 'altKey':\n return data.ctrlKey || data.metaKey;\n case 'ctrlKey':\n return data.altKey || data.metaKey;\n case 'metaKey':\n return data.ctrlKey || data.altKey;\n }\n return false;\n };\n ViewController.prototype.dispatchMouse = function (data) {\n if (data.middleButton) {\n if (data.inSelectionMode) {\n this._columnSelect(data.position, data.mouseColumn);\n }\n else {\n this.moveTo(data.position);\n }\n }\n else if (data.startedOnLineNumbers) {\n // If the dragging started on the gutter, then have operations work on the entire line\n if (this._hasMulticursorModifier(data)) {\n if (data.inSelectionMode) {\n this._lastCursorLineSelect(data.position);\n }\n else {\n this._createCursor(data.position, true);\n }\n }\n else {\n if (data.inSelectionMode) {\n this._lineSelectDrag(data.position);\n }\n else {\n this._lineSelect(data.position);\n }\n }\n }\n else if (data.mouseDownCount >= 4) {\n this._selectAll();\n }\n else if (data.mouseDownCount === 3) {\n if (this._hasMulticursorModifier(data)) {\n if (data.inSelectionMode) {\n this._lastCursorLineSelectDrag(data.position);\n }\n else {\n this._lastCursorLineSelect(data.position);\n }\n }\n else {\n if (data.inSelectionMode) {\n this._lineSelectDrag(data.position);\n }\n else {\n this._lineSelect(data.position);\n }\n }\n }\n else if (data.mouseDownCount === 2) {\n if (this._hasMulticursorModifier(data)) {\n this._lastCursorWordSelect(data.position);\n }\n else {\n if (data.inSelectionMode) {\n this._wordSelectDrag(data.position);\n }\n else {\n this._wordSelect(data.position);\n }\n }\n }\n else {\n if (this._hasMulticursorModifier(data)) {\n if (!this._hasNonMulticursorModifier(data)) {\n if (data.shiftKey) {\n this._columnSelect(data.position, data.mouseColumn);\n }\n else {\n // Do multi-cursor operations only when purely alt is pressed\n if (data.inSelectionMode) {\n this._lastCursorMoveToSelect(data.position);\n }\n else {\n this._createCursor(data.position, false);\n }\n }\n }\n }\n else {\n if (data.inSelectionMode) {\n if (data.altKey) {\n this._columnSelect(data.position, data.mouseColumn);\n }\n else {\n this._moveToSelect(data.position);\n }\n }\n else {\n this.moveTo(data.position);\n }\n }\n }\n };\n ViewController.prototype._usualArgs = function (viewPosition) {\n viewPosition = this._validateViewColumn(viewPosition);\n return {\n position: this._convertViewToModelPosition(viewPosition),\n viewPosition: viewPosition\n };\n };\n ViewController.prototype.moveTo = function (viewPosition) {\n this._execMouseCommand(CoreNavigationCommands.MoveTo, this._usualArgs(viewPosition));\n };\n ViewController.prototype._moveToSelect = function (viewPosition) {\n this._execMouseCommand(CoreNavigationCommands.MoveToSelect, this._usualArgs(viewPosition));\n };\n ViewController.prototype._columnSelect = function (viewPosition, mouseColumn) {\n viewPosition = this._validateViewColumn(viewPosition);\n this._execMouseCommand(CoreNavigationCommands.ColumnSelect, {\n position: this._convertViewToModelPosition(viewPosition),\n viewPosition: viewPosition,\n mouseColumn: mouseColumn\n });\n };\n ViewController.prototype._createCursor = function (viewPosition, wholeLine) {\n viewPosition = this._validateViewColumn(viewPosition);\n this._execMouseCommand(CoreNavigationCommands.CreateCursor, {\n position: this._convertViewToModelPosition(viewPosition),\n viewPosition: viewPosition,\n wholeLine: wholeLine\n });\n };\n ViewController.prototype._lastCursorMoveToSelect = function (viewPosition) {\n this._execMouseCommand(CoreNavigationCommands.LastCursorMoveToSelect, this._usualArgs(viewPosition));\n };\n ViewController.prototype._wordSelect = function (viewPosition) {\n this._execMouseCommand(CoreNavigationCommands.WordSelect, this._usualArgs(viewPosition));\n };\n ViewController.prototype._wordSelectDrag = function (viewPosition) {\n this._execMouseCommand(CoreNavigationCommands.WordSelectDrag, this._usualArgs(viewPosition));\n };\n ViewController.prototype._lastCursorWordSelect = function (viewPosition) {\n this._execMouseCommand(CoreNavigationCommands.LastCursorWordSelect, this._usualArgs(viewPosition));\n };\n ViewController.prototype._lineSelect = function (viewPosition) {\n this._execMouseCommand(CoreNavigationCommands.LineSelect, this._usualArgs(viewPosition));\n };\n ViewController.prototype._lineSelectDrag = function (viewPosition) {\n this._execMouseCommand(CoreNavigationCommands.LineSelectDrag, this._usualArgs(viewPosition));\n };\n ViewController.prototype._lastCursorLineSelect = function (viewPosition) {\n this._execMouseCommand(CoreNavigationCommands.LastCursorLineSelect, this._usualArgs(viewPosition));\n };\n ViewController.prototype._lastCursorLineSelectDrag = function (viewPosition) {\n this._execMouseCommand(CoreNavigationCommands.LastCursorLineSelectDrag, this._usualArgs(viewPosition));\n };\n ViewController.prototype._selectAll = function () {\n this._execMouseCommand(CoreNavigationCommands.SelectAll, {});\n };\n // ----------------------\n ViewController.prototype._convertViewToModelPosition = function (viewPosition) {\n return this.viewModel.coordinatesConverter.convertViewPositionToModelPosition(viewPosition);\n };\n ViewController.prototype.emitKeyDown = function (e) {\n this.outgoingEvents.emitKeyDown(e);\n };\n ViewController.prototype.emitKeyUp = function (e) {\n this.outgoingEvents.emitKeyUp(e);\n };\n ViewController.prototype.emitContextMenu = function (e) {\n this.outgoingEvents.emitContextMenu(e);\n };\n ViewController.prototype.emitMouseMove = function (e) {\n this.outgoingEvents.emitMouseMove(e);\n };\n ViewController.prototype.emitMouseLeave = function (e) {\n this.outgoingEvents.emitMouseLeave(e);\n };\n ViewController.prototype.emitMouseUp = function (e) {\n this.outgoingEvents.emitMouseUp(e);\n };\n ViewController.prototype.emitMouseDown = function (e) {\n this.outgoingEvents.emitMouseDown(e);\n };\n ViewController.prototype.emitMouseDrag = function (e) {\n this.outgoingEvents.emitMouseDrag(e);\n };\n ViewController.prototype.emitMouseDrop = function (e) {\n this.outgoingEvents.emitMouseDrop(e);\n };\n ViewController.prototype.emitMouseWheel = function (e) {\n this.outgoingEvents.emitMouseWheel(e);\n };\n return ViewController;\n}());\nexport { ViewController };\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport { createFastDomNode } from '../../../base/browser/fastDomNode.js';\nimport { createStringBuilder } from '../../common/core/stringBuilder.js';\nvar RenderedLinesCollection = /** @class */ (function () {\n function RenderedLinesCollection(createLine) {\n this._createLine = createLine;\n this._set(1, []);\n }\n RenderedLinesCollection.prototype.flush = function () {\n this._set(1, []);\n };\n RenderedLinesCollection.prototype._set = function (rendLineNumberStart, lines) {\n this._lines = lines;\n this._rendLineNumberStart = rendLineNumberStart;\n };\n RenderedLinesCollection.prototype._get = function () {\n return {\n rendLineNumberStart: this._rendLineNumberStart,\n lines: this._lines\n };\n };\n /**\n * @returns Inclusive line number that is inside this collection\n */\n RenderedLinesCollection.prototype.getStartLineNumber = function () {\n return this._rendLineNumberStart;\n };\n /**\n * @returns Inclusive line number that is inside this collection\n */\n RenderedLinesCollection.prototype.getEndLineNumber = function () {\n return this._rendLineNumberStart + this._lines.length - 1;\n };\n RenderedLinesCollection.prototype.getCount = function () {\n return this._lines.length;\n };\n RenderedLinesCollection.prototype.getLine = function (lineNumber) {\n var lineIndex = lineNumber - this._rendLineNumberStart;\n if (lineIndex < 0 || lineIndex >= this._lines.length) {\n throw new Error('Illegal value for lineNumber');\n }\n return this._lines[lineIndex];\n };\n /**\n * @returns Lines that were removed from this collection\n */\n RenderedLinesCollection.prototype.onLinesDeleted = function (deleteFromLineNumber, deleteToLineNumber) {\n if (this.getCount() === 0) {\n // no lines\n return null;\n }\n var startLineNumber = this.getStartLineNumber();\n var endLineNumber = this.getEndLineNumber();\n if (deleteToLineNumber < startLineNumber) {\n // deleting above the viewport\n var deleteCnt = deleteToLineNumber - deleteFromLineNumber + 1;\n this._rendLineNumberStart -= deleteCnt;\n return null;\n }\n if (deleteFromLineNumber > endLineNumber) {\n // deleted below the viewport\n return null;\n }\n // Record what needs to be deleted\n var deleteStartIndex = 0;\n var deleteCount = 0;\n for (var lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {\n var lineIndex = lineNumber - this._rendLineNumberStart;\n if (deleteFromLineNumber <= lineNumber && lineNumber <= deleteToLineNumber) {\n // this is a line to be deleted\n if (deleteCount === 0) {\n // this is the first line to be deleted\n deleteStartIndex = lineIndex;\n deleteCount = 1;\n }\n else {\n deleteCount++;\n }\n }\n }\n // Adjust this._rendLineNumberStart for lines deleted above\n if (deleteFromLineNumber < startLineNumber) {\n // Something was deleted above\n var deleteAboveCount = 0;\n if (deleteToLineNumber < startLineNumber) {\n // the entire deleted lines are above\n deleteAboveCount = deleteToLineNumber - deleteFromLineNumber + 1;\n }\n else {\n deleteAboveCount = startLineNumber - deleteFromLineNumber;\n }\n this._rendLineNumberStart -= deleteAboveCount;\n }\n var deleted = this._lines.splice(deleteStartIndex, deleteCount);\n return deleted;\n };\n RenderedLinesCollection.prototype.onLinesChanged = function (changeFromLineNumber, changeToLineNumber) {\n if (this.getCount() === 0) {\n // no lines\n return false;\n }\n var startLineNumber = this.getStartLineNumber();\n var endLineNumber = this.getEndLineNumber();\n var someoneNotified = false;\n for (var changedLineNumber = changeFromLineNumber; changedLineNumber <= changeToLineNumber; changedLineNumber++) {\n if (changedLineNumber >= startLineNumber && changedLineNumber <= endLineNumber) {\n // Notify the line\n this._lines[changedLineNumber - this._rendLineNumberStart].onContentChanged();\n someoneNotified = true;\n }\n }\n return someoneNotified;\n };\n RenderedLinesCollection.prototype.onLinesInserted = function (insertFromLineNumber, insertToLineNumber) {\n if (this.getCount() === 0) {\n // no lines\n return null;\n }\n var insertCnt = insertToLineNumber - insertFromLineNumber + 1;\n var startLineNumber = this.getStartLineNumber();\n var endLineNumber = this.getEndLineNumber();\n if (insertFromLineNumber <= startLineNumber) {\n // inserting above the viewport\n this._rendLineNumberStart += insertCnt;\n return null;\n }\n if (insertFromLineNumber > endLineNumber) {\n // inserting below the viewport\n return null;\n }\n if (insertCnt + insertFromLineNumber > endLineNumber) {\n // insert inside the viewport in such a way that all remaining lines are pushed outside\n var deleted = this._lines.splice(insertFromLineNumber - this._rendLineNumberStart, endLineNumber - insertFromLineNumber + 1);\n return deleted;\n }\n // insert inside the viewport, push out some lines, but not all remaining lines\n var newLines = [];\n for (var i = 0; i < insertCnt; i++) {\n newLines[i] = this._createLine();\n }\n var insertIndex = insertFromLineNumber - this._rendLineNumberStart;\n var beforeLines = this._lines.slice(0, insertIndex);\n var afterLines = this._lines.slice(insertIndex, this._lines.length - insertCnt);\n var deletedLines = this._lines.slice(this._lines.length - insertCnt, this._lines.length);\n this._lines = beforeLines.concat(newLines).concat(afterLines);\n return deletedLines;\n };\n RenderedLinesCollection.prototype.onTokensChanged = function (ranges) {\n if (this.getCount() === 0) {\n // no lines\n return false;\n }\n var startLineNumber = this.getStartLineNumber();\n var endLineNumber = this.getEndLineNumber();\n var notifiedSomeone = false;\n for (var i = 0, len = ranges.length; i < len; i++) {\n var rng = ranges[i];\n if (rng.toLineNumber < startLineNumber || rng.fromLineNumber > endLineNumber) {\n // range outside viewport\n continue;\n }\n var from = Math.max(startLineNumber, rng.fromLineNumber);\n var to = Math.min(endLineNumber, rng.toLineNumber);\n for (var lineNumber = from; lineNumber <= to; lineNumber++) {\n var lineIndex = lineNumber - this._rendLineNumberStart;\n this._lines[lineIndex].onTokensChanged();\n notifiedSomeone = true;\n }\n }\n return notifiedSomeone;\n };\n return RenderedLinesCollection;\n}());\nexport { RenderedLinesCollection };\nvar VisibleLinesCollection = /** @class */ (function () {\n function VisibleLinesCollection(host) {\n var _this = this;\n this._host = host;\n this.domNode = this._createDomNode();\n this._linesCollection = new RenderedLinesCollection(function () { return _this._host.createVisibleLine(); });\n }\n VisibleLinesCollection.prototype._createDomNode = function () {\n var domNode = createFastDomNode(document.createElement('div'));\n domNode.setClassName('view-layer');\n domNode.setPosition('absolute');\n domNode.domNode.setAttribute('role', 'presentation');\n domNode.domNode.setAttribute('aria-hidden', 'true');\n return domNode;\n };\n // ---- begin view event handlers\n VisibleLinesCollection.prototype.onConfigurationChanged = function (e) {\n return e.layoutInfo;\n };\n VisibleLinesCollection.prototype.onFlushed = function (e) {\n this._linesCollection.flush();\n // No need to clear the dom node because a full .innerHTML will occur in ViewLayerRenderer._render\n return true;\n };\n VisibleLinesCollection.prototype.onLinesChanged = function (e) {\n return this._linesCollection.onLinesChanged(e.fromLineNumber, e.toLineNumber);\n };\n VisibleLinesCollection.prototype.onLinesDeleted = function (e) {\n var deleted = this._linesCollection.onLinesDeleted(e.fromLineNumber, e.toLineNumber);\n if (deleted) {\n // Remove from DOM\n for (var i = 0, len = deleted.length; i < len; i++) {\n var lineDomNode = deleted[i].getDomNode();\n if (lineDomNode) {\n this.domNode.domNode.removeChild(lineDomNode);\n }\n }\n }\n return true;\n };\n VisibleLinesCollection.prototype.onLinesInserted = function (e) {\n var deleted = this._linesCollection.onLinesInserted(e.fromLineNumber, e.toLineNumber);\n if (deleted) {\n // Remove from DOM\n for (var i = 0, len = deleted.length; i < len; i++) {\n var lineDomNode = deleted[i].getDomNode();\n if (lineDomNode) {\n this.domNode.domNode.removeChild(lineDomNode);\n }\n }\n }\n return true;\n };\n VisibleLinesCollection.prototype.onScrollChanged = function (e) {\n return e.scrollTopChanged;\n };\n VisibleLinesCollection.prototype.onTokensChanged = function (e) {\n return this._linesCollection.onTokensChanged(e.ranges);\n };\n VisibleLinesCollection.prototype.onZonesChanged = function (e) {\n return true;\n };\n // ---- end view event handlers\n VisibleLinesCollection.prototype.getStartLineNumber = function () {\n return this._linesCollection.getStartLineNumber();\n };\n VisibleLinesCollection.prototype.getEndLineNumber = function () {\n return this._linesCollection.getEndLineNumber();\n };\n VisibleLinesCollection.prototype.getVisibleLine = function (lineNumber) {\n return this._linesCollection.getLine(lineNumber);\n };\n VisibleLinesCollection.prototype.renderLines = function (viewportData) {\n var inp = this._linesCollection._get();\n var renderer = new ViewLayerRenderer(this.domNode.domNode, this._host, viewportData);\n var ctx = {\n rendLineNumberStart: inp.rendLineNumberStart,\n lines: inp.lines,\n linesLength: inp.lines.length\n };\n // Decide if this render will do a single update (single large .innerHTML) or many updates (inserting/removing dom nodes)\n var resCtx = renderer.render(ctx, viewportData.startLineNumber, viewportData.endLineNumber, viewportData.relativeVerticalOffset);\n this._linesCollection._set(resCtx.rendLineNumberStart, resCtx.lines);\n };\n return VisibleLinesCollection;\n}());\nexport { VisibleLinesCollection };\nvar ViewLayerRenderer = /** @class */ (function () {\n function ViewLayerRenderer(domNode, host, viewportData) {\n this.domNode = domNode;\n this.host = host;\n this.viewportData = viewportData;\n }\n ViewLayerRenderer.prototype.render = function (inContext, startLineNumber, stopLineNumber, deltaTop) {\n var ctx = {\n rendLineNumberStart: inContext.rendLineNumberStart,\n lines: inContext.lines.slice(0),\n linesLength: inContext.linesLength\n };\n if ((ctx.rendLineNumberStart + ctx.linesLength - 1 < startLineNumber) || (stopLineNumber < ctx.rendLineNumberStart)) {\n // There is no overlap whatsoever\n ctx.rendLineNumberStart = startLineNumber;\n ctx.linesLength = stopLineNumber - startLineNumber + 1;\n ctx.lines = [];\n for (var x = startLineNumber; x <= stopLineNumber; x++) {\n ctx.lines[x - startLineNumber] = this.host.createVisibleLine();\n }\n this._finishRendering(ctx, true, deltaTop);\n return ctx;\n }\n // Update lines which will remain untouched\n this._renderUntouchedLines(ctx, Math.max(startLineNumber - ctx.rendLineNumberStart, 0), Math.min(stopLineNumber - ctx.rendLineNumberStart, ctx.linesLength - 1), deltaTop, startLineNumber);\n if (ctx.rendLineNumberStart > startLineNumber) {\n // Insert lines before\n var fromLineNumber = startLineNumber;\n var toLineNumber = Math.min(stopLineNumber, ctx.rendLineNumberStart - 1);\n if (fromLineNumber <= toLineNumber) {\n this._insertLinesBefore(ctx, fromLineNumber, toLineNumber, deltaTop, startLineNumber);\n ctx.linesLength += toLineNumber - fromLineNumber + 1;\n }\n }\n else if (ctx.rendLineNumberStart < startLineNumber) {\n // Remove lines before\n var removeCnt = Math.min(ctx.linesLength, startLineNumber - ctx.rendLineNumberStart);\n if (removeCnt > 0) {\n this._removeLinesBefore(ctx, removeCnt);\n ctx.linesLength -= removeCnt;\n }\n }\n ctx.rendLineNumberStart = startLineNumber;\n if (ctx.rendLineNumberStart + ctx.linesLength - 1 < stopLineNumber) {\n // Insert lines after\n var fromLineNumber = ctx.rendLineNumberStart + ctx.linesLength;\n var toLineNumber = stopLineNumber;\n if (fromLineNumber <= toLineNumber) {\n this._insertLinesAfter(ctx, fromLineNumber, toLineNumber, deltaTop, startLineNumber);\n ctx.linesLength += toLineNumber - fromLineNumber + 1;\n }\n }\n else if (ctx.rendLineNumberStart + ctx.linesLength - 1 > stopLineNumber) {\n // Remove lines after\n var fromLineNumber = Math.max(0, stopLineNumber - ctx.rendLineNumberStart + 1);\n var toLineNumber = ctx.linesLength - 1;\n var removeCnt = toLineNumber - fromLineNumber + 1;\n if (removeCnt > 0) {\n this._removeLinesAfter(ctx, removeCnt);\n ctx.linesLength -= removeCnt;\n }\n }\n this._finishRendering(ctx, false, deltaTop);\n return ctx;\n };\n ViewLayerRenderer.prototype._renderUntouchedLines = function (ctx, startIndex, endIndex, deltaTop, deltaLN) {\n var rendLineNumberStart = ctx.rendLineNumberStart;\n var lines = ctx.lines;\n for (var i = startIndex; i <= endIndex; i++) {\n var lineNumber = rendLineNumberStart + i;\n lines[i].layoutLine(lineNumber, deltaTop[lineNumber - deltaLN]);\n }\n };\n ViewLayerRenderer.prototype._insertLinesBefore = function (ctx, fromLineNumber, toLineNumber, deltaTop, deltaLN) {\n var newLines = [];\n var newLinesLen = 0;\n for (var lineNumber = fromLineNumber; lineNumber <= toLineNumber; lineNumber++) {\n newLines[newLinesLen++] = this.host.createVisibleLine();\n }\n ctx.lines = newLines.concat(ctx.lines);\n };\n ViewLayerRenderer.prototype._removeLinesBefore = function (ctx, removeCount) {\n for (var i = 0; i < removeCount; i++) {\n var lineDomNode = ctx.lines[i].getDomNode();\n if (lineDomNode) {\n this.domNode.removeChild(lineDomNode);\n }\n }\n ctx.lines.splice(0, removeCount);\n };\n ViewLayerRenderer.prototype._insertLinesAfter = function (ctx, fromLineNumber, toLineNumber, deltaTop, deltaLN) {\n var newLines = [];\n var newLinesLen = 0;\n for (var lineNumber = fromLineNumber; lineNumber <= toLineNumber; lineNumber++) {\n newLines[newLinesLen++] = this.host.createVisibleLine();\n }\n ctx.lines = ctx.lines.concat(newLines);\n };\n ViewLayerRenderer.prototype._removeLinesAfter = function (ctx, removeCount) {\n var removeIndex = ctx.linesLength - removeCount;\n for (var i = 0; i < removeCount; i++) {\n var lineDomNode = ctx.lines[removeIndex + i].getDomNode();\n if (lineDomNode) {\n this.domNode.removeChild(lineDomNode);\n }\n }\n ctx.lines.splice(removeIndex, removeCount);\n };\n ViewLayerRenderer.prototype._finishRenderingNewLines = function (ctx, domNodeIsEmpty, newLinesHTML, wasNew) {\n var lastChild = this.domNode.lastChild;\n if (domNodeIsEmpty || !lastChild) {\n this.domNode.innerHTML = newLinesHTML;\n }\n else {\n lastChild.insertAdjacentHTML('afterend', newLinesHTML);\n }\n var currChild = this.domNode.lastChild;\n for (var i = ctx.linesLength - 1; i >= 0; i--) {\n var line = ctx.lines[i];\n if (wasNew[i]) {\n line.setDomNode(currChild);\n currChild = currChild.previousSibling;\n }\n }\n };\n ViewLayerRenderer.prototype._finishRenderingInvalidLines = function (ctx, invalidLinesHTML, wasInvalid) {\n var hugeDomNode = document.createElement('div');\n hugeDomNode.innerHTML = invalidLinesHTML;\n for (var i = 0; i < ctx.linesLength; i++) {\n var line = ctx.lines[i];\n if (wasInvalid[i]) {\n var source = hugeDomNode.firstChild;\n var lineDomNode = line.getDomNode();\n lineDomNode.parentNode.replaceChild(source, lineDomNode);\n line.setDomNode(source);\n }\n }\n };\n ViewLayerRenderer.prototype._finishRendering = function (ctx, domNodeIsEmpty, deltaTop) {\n var sb = ViewLayerRenderer._sb;\n var linesLength = ctx.linesLength;\n var lines = ctx.lines;\n var rendLineNumberStart = ctx.rendLineNumberStart;\n var wasNew = [];\n {\n sb.reset();\n var hadNewLine = false;\n for (var i = 0; i < linesLength; i++) {\n var line = lines[i];\n wasNew[i] = false;\n var lineDomNode = line.getDomNode();\n if (lineDomNode) {\n // line is not new\n continue;\n }\n var renderResult = line.renderLine(i + rendLineNumberStart, deltaTop[i], this.viewportData, sb);\n if (!renderResult) {\n // line does not need rendering\n continue;\n }\n wasNew[i] = true;\n hadNewLine = true;\n }\n if (hadNewLine) {\n this._finishRenderingNewLines(ctx, domNodeIsEmpty, sb.build(), wasNew);\n }\n }\n {\n sb.reset();\n var hadInvalidLine = false;\n var wasInvalid = [];\n for (var i = 0; i < linesLength; i++) {\n var line = lines[i];\n wasInvalid[i] = false;\n if (wasNew[i]) {\n // line was new\n continue;\n }\n var renderResult = line.renderLine(i + rendLineNumberStart, deltaTop[i], this.viewportData, sb);\n if (!renderResult) {\n // line does not need rendering\n continue;\n }\n wasInvalid[i] = true;\n hadInvalidLine = true;\n }\n if (hadInvalidLine) {\n this._finishRenderingInvalidLines(ctx, sb.build(), wasInvalid);\n }\n }\n };\n ViewLayerRenderer._sb = createStringBuilder(100000);\n return ViewLayerRenderer;\n}());\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { createFastDomNode } from '../../../base/browser/fastDomNode.js';\nimport { Configuration } from '../config/configuration.js';\nimport { VisibleLinesCollection } from './viewLayer.js';\nimport { ViewPart } from './viewPart.js';\nvar ViewOverlays = /** @class */ (function (_super) {\n __extends(ViewOverlays, _super);\n function ViewOverlays(context) {\n var _this = _super.call(this, context) || this;\n _this._visibleLines = new VisibleLinesCollection(_this);\n _this.domNode = _this._visibleLines.domNode;\n _this._dynamicOverlays = [];\n _this._isFocused = false;\n _this.domNode.setClassName('view-overlays');\n return _this;\n }\n ViewOverlays.prototype.shouldRender = function () {\n if (_super.prototype.shouldRender.call(this)) {\n return true;\n }\n for (var i = 0, len = this._dynamicOverlays.length; i < len; i++) {\n var dynamicOverlay = this._dynamicOverlays[i];\n if (dynamicOverlay.shouldRender()) {\n return true;\n }\n }\n return false;\n };\n ViewOverlays.prototype.dispose = function () {\n _super.prototype.dispose.call(this);\n for (var i = 0, len = this._dynamicOverlays.length; i < len; i++) {\n var dynamicOverlay = this._dynamicOverlays[i];\n dynamicOverlay.dispose();\n }\n this._dynamicOverlays = [];\n };\n ViewOverlays.prototype.getDomNode = function () {\n return this.domNode;\n };\n // ---- begin IVisibleLinesHost\n ViewOverlays.prototype.createVisibleLine = function () {\n return new ViewOverlayLine(this._context.configuration, this._dynamicOverlays);\n };\n // ---- end IVisibleLinesHost\n ViewOverlays.prototype.addDynamicOverlay = function (overlay) {\n this._dynamicOverlays.push(overlay);\n };\n // ----- event handlers\n ViewOverlays.prototype.onConfigurationChanged = function (e) {\n this._visibleLines.onConfigurationChanged(e);\n var startLineNumber = this._visibleLines.getStartLineNumber();\n var endLineNumber = this._visibleLines.getEndLineNumber();\n for (var lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {\n var line = this._visibleLines.getVisibleLine(lineNumber);\n line.onConfigurationChanged(e);\n }\n return true;\n };\n ViewOverlays.prototype.onFlushed = function (e) {\n return this._visibleLines.onFlushed(e);\n };\n ViewOverlays.prototype.onFocusChanged = function (e) {\n this._isFocused = e.isFocused;\n return true;\n };\n ViewOverlays.prototype.onLinesChanged = function (e) {\n return this._visibleLines.onLinesChanged(e);\n };\n ViewOverlays.prototype.onLinesDeleted = function (e) {\n return this._visibleLines.onLinesDeleted(e);\n };\n ViewOverlays.prototype.onLinesInserted = function (e) {\n return this._visibleLines.onLinesInserted(e);\n };\n ViewOverlays.prototype.onScrollChanged = function (e) {\n return this._visibleLines.onScrollChanged(e) || true;\n };\n ViewOverlays.prototype.onTokensChanged = function (e) {\n return this._visibleLines.onTokensChanged(e);\n };\n ViewOverlays.prototype.onZonesChanged = function (e) {\n return this._visibleLines.onZonesChanged(e);\n };\n // ----- end event handlers\n ViewOverlays.prototype.prepareRender = function (ctx) {\n var toRender = this._dynamicOverlays.filter(function (overlay) { return overlay.shouldRender(); });\n for (var i = 0, len = toRender.length; i < len; i++) {\n var dynamicOverlay = toRender[i];\n dynamicOverlay.prepareRender(ctx);\n dynamicOverlay.onDidRender();\n }\n };\n ViewOverlays.prototype.render = function (ctx) {\n // Overwriting to bypass `shouldRender` flag\n this._viewOverlaysRender(ctx);\n this.domNode.toggleClassName('focused', this._isFocused);\n };\n ViewOverlays.prototype._viewOverlaysRender = function (ctx) {\n this._visibleLines.renderLines(ctx.viewportData);\n };\n return ViewOverlays;\n}(ViewPart));\nexport { ViewOverlays };\nvar ViewOverlayLine = /** @class */ (function () {\n function ViewOverlayLine(configuration, dynamicOverlays) {\n this._configuration = configuration;\n this._lineHeight = this._configuration.editor.lineHeight;\n this._dynamicOverlays = dynamicOverlays;\n this._domNode = null;\n this._renderedContent = null;\n }\n ViewOverlayLine.prototype.getDomNode = function () {\n if (!this._domNode) {\n return null;\n }\n return this._domNode.domNode;\n };\n ViewOverlayLine.prototype.setDomNode = function (domNode) {\n this._domNode = createFastDomNode(domNode);\n };\n ViewOverlayLine.prototype.onContentChanged = function () {\n // Nothing\n };\n ViewOverlayLine.prototype.onTokensChanged = function () {\n // Nothing\n };\n ViewOverlayLine.prototype.onConfigurationChanged = function (e) {\n if (e.lineHeight) {\n this._lineHeight = this._configuration.editor.lineHeight;\n }\n };\n ViewOverlayLine.prototype.renderLine = function (lineNumber, deltaTop, viewportData, sb) {\n var result = '';\n for (var i = 0, len = this._dynamicOverlays.length; i < len; i++) {\n var dynamicOverlay = this._dynamicOverlays[i];\n result += dynamicOverlay.render(viewportData.startLineNumber, lineNumber);\n }\n if (this._renderedContent === result) {\n // No rendering needed\n return false;\n }\n this._renderedContent = result;\n sb.appendASCIIString('= this._renderResult.length) {\n return '';\n }\n return this._renderResult[lineIndex];\n };\n return GlyphMarginOverlay;\n}(DedupOverlay));\nexport { GlyphMarginOverlay };\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport './indentGuides.css';\nimport { DynamicViewOverlay } from '../../view/dynamicViewOverlay.js';\nimport { Position } from '../../../common/core/position.js';\nimport { editorActiveIndentGuides, editorIndentGuides } from '../../../common/view/editorColorRegistry.js';\nimport { registerThemingParticipant } from '../../../../platform/theme/common/themeService.js';\nvar IndentGuidesOverlay = /** @class */ (function (_super) {\n __extends(IndentGuidesOverlay, _super);\n function IndentGuidesOverlay(context) {\n var _this = _super.call(this) || this;\n _this._context = context;\n _this._primaryLineNumber = 0;\n _this._lineHeight = _this._context.configuration.editor.lineHeight;\n _this._spaceWidth = _this._context.configuration.editor.fontInfo.spaceWidth;\n _this._enabled = _this._context.configuration.editor.viewInfo.renderIndentGuides;\n _this._activeIndentEnabled = _this._context.configuration.editor.viewInfo.highlightActiveIndentGuide;\n _this._renderResult = null;\n _this._context.addEventHandler(_this);\n return _this;\n }\n IndentGuidesOverlay.prototype.dispose = function () {\n this._context.removeEventHandler(this);\n this._renderResult = null;\n _super.prototype.dispose.call(this);\n };\n // --- begin event handlers\n IndentGuidesOverlay.prototype.onConfigurationChanged = function (e) {\n if (e.lineHeight) {\n this._lineHeight = this._context.configuration.editor.lineHeight;\n }\n if (e.fontInfo) {\n this._spaceWidth = this._context.configuration.editor.fontInfo.spaceWidth;\n }\n if (e.viewInfo) {\n this._enabled = this._context.configuration.editor.viewInfo.renderIndentGuides;\n this._activeIndentEnabled = this._context.configuration.editor.viewInfo.highlightActiveIndentGuide;\n }\n return true;\n };\n IndentGuidesOverlay.prototype.onCursorStateChanged = function (e) {\n var selection = e.selections[0];\n var newPrimaryLineNumber = selection.isEmpty() ? selection.positionLineNumber : 0;\n if (this._primaryLineNumber !== newPrimaryLineNumber) {\n this._primaryLineNumber = newPrimaryLineNumber;\n return true;\n }\n return false;\n };\n IndentGuidesOverlay.prototype.onDecorationsChanged = function (e) {\n // true for inline decorations\n return true;\n };\n IndentGuidesOverlay.prototype.onFlushed = function (e) {\n return true;\n };\n IndentGuidesOverlay.prototype.onLinesChanged = function (e) {\n return true;\n };\n IndentGuidesOverlay.prototype.onLinesDeleted = function (e) {\n return true;\n };\n IndentGuidesOverlay.prototype.onLinesInserted = function (e) {\n return true;\n };\n IndentGuidesOverlay.prototype.onScrollChanged = function (e) {\n return e.scrollTopChanged; // || e.scrollWidthChanged;\n };\n IndentGuidesOverlay.prototype.onZonesChanged = function (e) {\n return true;\n };\n IndentGuidesOverlay.prototype.onLanguageConfigurationChanged = function (e) {\n return true;\n };\n // --- end event handlers\n IndentGuidesOverlay.prototype.prepareRender = function (ctx) {\n if (!this._enabled) {\n this._renderResult = null;\n return;\n }\n var visibleStartLineNumber = ctx.visibleRange.startLineNumber;\n var visibleEndLineNumber = ctx.visibleRange.endLineNumber;\n var indentSize = this._context.model.getOptions().indentSize;\n var indentWidth = indentSize * this._spaceWidth;\n var scrollWidth = ctx.scrollWidth;\n var lineHeight = this._lineHeight;\n var indents = this._context.model.getLinesIndentGuides(visibleStartLineNumber, visibleEndLineNumber);\n var activeIndentStartLineNumber = 0;\n var activeIndentEndLineNumber = 0;\n var activeIndentLevel = 0;\n if (this._activeIndentEnabled && this._primaryLineNumber) {\n var activeIndentInfo = this._context.model.getActiveIndentGuide(this._primaryLineNumber, visibleStartLineNumber, visibleEndLineNumber);\n activeIndentStartLineNumber = activeIndentInfo.startLineNumber;\n activeIndentEndLineNumber = activeIndentInfo.endLineNumber;\n activeIndentLevel = activeIndentInfo.indent;\n }\n var output = [];\n for (var lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {\n var containsActiveIndentGuide = (activeIndentStartLineNumber <= lineNumber && lineNumber <= activeIndentEndLineNumber);\n var lineIndex = lineNumber - visibleStartLineNumber;\n var indent = indents[lineIndex];\n var result = '';\n var leftMostVisiblePosition = ctx.visibleRangeForPosition(new Position(lineNumber, 1));\n var left = leftMostVisiblePosition ? leftMostVisiblePosition.left : 0;\n for (var i = 1; i <= indent; i++) {\n var className = (containsActiveIndentGuide && i === activeIndentLevel ? 'cigra' : 'cigr');\n result += \"
\";\n left += indentWidth;\n if (left > scrollWidth) {\n break;\n }\n }\n output[lineIndex] = result;\n }\n this._renderResult = output;\n };\n IndentGuidesOverlay.prototype.render = function (startLineNumber, lineNumber) {\n if (!this._renderResult) {\n return '';\n }\n var lineIndex = lineNumber - startLineNumber;\n if (lineIndex < 0 || lineIndex >= this._renderResult.length) {\n return '';\n }\n return this._renderResult[lineIndex];\n };\n return IndentGuidesOverlay;\n}(DynamicViewOverlay));\nexport { IndentGuidesOverlay };\nregisterThemingParticipant(function (theme, collector) {\n var editorIndentGuidesColor = theme.getColor(editorIndentGuides);\n if (editorIndentGuidesColor) {\n collector.addRule(\".monaco-editor .lines-content .cigr { box-shadow: 1px 0 0 0 \" + editorIndentGuidesColor + \" inset; }\");\n }\n var editorActiveIndentGuidesColor = theme.getColor(editorActiveIndentGuides) || editorIndentGuidesColor;\n if (editorActiveIndentGuidesColor) {\n collector.addRule(\".monaco-editor .lines-content .cigra { box-shadow: 1px 0 0 0 \" + editorActiveIndentGuidesColor + \" inset; }\");\n }\n});\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport './viewLines.css';\nimport { RunOnceScheduler } from '../../../../base/common/async.js';\nimport { Configuration } from '../../config/configuration.js';\nimport { VisibleLinesCollection } from '../../view/viewLayer.js';\nimport { PartFingerprints, ViewPart } from '../../view/viewPart.js';\nimport { DomReadingContext, ViewLine, ViewLineOptions } from './viewLine.js';\nimport { Position } from '../../../common/core/position.js';\nimport { Range } from '../../../common/core/range.js';\nimport { LineVisibleRanges } from '../../../common/view/renderingContext.js';\nvar LastRenderedData = /** @class */ (function () {\n function LastRenderedData() {\n this._currentVisibleRange = new Range(1, 1, 1, 1);\n }\n LastRenderedData.prototype.getCurrentVisibleRange = function () {\n return this._currentVisibleRange;\n };\n LastRenderedData.prototype.setCurrentVisibleRange = function (currentVisibleRange) {\n this._currentVisibleRange = currentVisibleRange;\n };\n return LastRenderedData;\n}());\nvar HorizontalRevealRequest = /** @class */ (function () {\n function HorizontalRevealRequest(lineNumber, startColumn, endColumn, startScrollTop, stopScrollTop, scrollType) {\n this.lineNumber = lineNumber;\n this.startColumn = startColumn;\n this.endColumn = endColumn;\n this.startScrollTop = startScrollTop;\n this.stopScrollTop = stopScrollTop;\n this.scrollType = scrollType;\n }\n return HorizontalRevealRequest;\n}());\nvar ViewLines = /** @class */ (function (_super) {\n __extends(ViewLines, _super);\n function ViewLines(context, linesContent) {\n var _this = _super.call(this, context) || this;\n _this._linesContent = linesContent;\n _this._textRangeRestingSpot = document.createElement('div');\n _this._visibleLines = new VisibleLinesCollection(_this);\n _this.domNode = _this._visibleLines.domNode;\n var conf = _this._context.configuration;\n _this._lineHeight = conf.editor.lineHeight;\n _this._typicalHalfwidthCharacterWidth = conf.editor.fontInfo.typicalHalfwidthCharacterWidth;\n _this._isViewportWrapping = conf.editor.wrappingInfo.isViewportWrapping;\n _this._revealHorizontalRightPadding = conf.editor.viewInfo.revealHorizontalRightPadding;\n _this._canUseLayerHinting = conf.editor.canUseLayerHinting;\n _this._viewLineOptions = new ViewLineOptions(conf, _this._context.theme.type);\n PartFingerprints.write(_this.domNode, 7 /* ViewLines */);\n _this.domNode.setClassName('view-lines');\n Configuration.applyFontInfo(_this.domNode, conf.editor.fontInfo);\n // --- width & height\n _this._maxLineWidth = 0;\n _this._asyncUpdateLineWidths = new RunOnceScheduler(function () {\n _this._updateLineWidthsSlow();\n }, 200);\n _this._lastRenderedData = new LastRenderedData();\n _this._horizontalRevealRequest = null;\n return _this;\n }\n ViewLines.prototype.dispose = function () {\n this._asyncUpdateLineWidths.dispose();\n _super.prototype.dispose.call(this);\n };\n ViewLines.prototype.getDomNode = function () {\n return this.domNode;\n };\n // ---- begin IVisibleLinesHost\n ViewLines.prototype.createVisibleLine = function () {\n return new ViewLine(this._viewLineOptions);\n };\n // ---- end IVisibleLinesHost\n // ---- begin view event handlers\n ViewLines.prototype.onConfigurationChanged = function (e) {\n this._visibleLines.onConfigurationChanged(e);\n if (e.wrappingInfo) {\n this._maxLineWidth = 0;\n }\n var conf = this._context.configuration;\n if (e.lineHeight) {\n this._lineHeight = conf.editor.lineHeight;\n }\n if (e.fontInfo) {\n this._typicalHalfwidthCharacterWidth = conf.editor.fontInfo.typicalHalfwidthCharacterWidth;\n }\n if (e.wrappingInfo) {\n this._isViewportWrapping = conf.editor.wrappingInfo.isViewportWrapping;\n }\n if (e.viewInfo) {\n this._revealHorizontalRightPadding = conf.editor.viewInfo.revealHorizontalRightPadding;\n }\n if (e.canUseLayerHinting) {\n this._canUseLayerHinting = conf.editor.canUseLayerHinting;\n }\n if (e.fontInfo) {\n Configuration.applyFontInfo(this.domNode, conf.editor.fontInfo);\n }\n this._onOptionsMaybeChanged();\n if (e.layoutInfo) {\n this._maxLineWidth = 0;\n }\n return true;\n };\n ViewLines.prototype._onOptionsMaybeChanged = function () {\n var conf = this._context.configuration;\n var newViewLineOptions = new ViewLineOptions(conf, this._context.theme.type);\n if (!this._viewLineOptions.equals(newViewLineOptions)) {\n this._viewLineOptions = newViewLineOptions;\n var startLineNumber = this._visibleLines.getStartLineNumber();\n var endLineNumber = this._visibleLines.getEndLineNumber();\n for (var lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {\n var line = this._visibleLines.getVisibleLine(lineNumber);\n line.onOptionsChanged(this._viewLineOptions);\n }\n return true;\n }\n return false;\n };\n ViewLines.prototype.onCursorStateChanged = function (e) {\n var rendStartLineNumber = this._visibleLines.getStartLineNumber();\n var rendEndLineNumber = this._visibleLines.getEndLineNumber();\n var r = false;\n for (var lineNumber = rendStartLineNumber; lineNumber <= rendEndLineNumber; lineNumber++) {\n r = this._visibleLines.getVisibleLine(lineNumber).onSelectionChanged() || r;\n }\n return r;\n };\n ViewLines.prototype.onDecorationsChanged = function (e) {\n if (true /*e.inlineDecorationsChanged*/) {\n var rendStartLineNumber = this._visibleLines.getStartLineNumber();\n var rendEndLineNumber = this._visibleLines.getEndLineNumber();\n for (var lineNumber = rendStartLineNumber; lineNumber <= rendEndLineNumber; lineNumber++) {\n this._visibleLines.getVisibleLine(lineNumber).onDecorationsChanged();\n }\n }\n return true;\n };\n ViewLines.prototype.onFlushed = function (e) {\n var shouldRender = this._visibleLines.onFlushed(e);\n this._maxLineWidth = 0;\n return shouldRender;\n };\n ViewLines.prototype.onLinesChanged = function (e) {\n return this._visibleLines.onLinesChanged(e);\n };\n ViewLines.prototype.onLinesDeleted = function (e) {\n return this._visibleLines.onLinesDeleted(e);\n };\n ViewLines.prototype.onLinesInserted = function (e) {\n return this._visibleLines.onLinesInserted(e);\n };\n ViewLines.prototype.onRevealRangeRequest = function (e) {\n // Using the future viewport here in order to handle multiple\n // incoming reveal range requests that might all desire to be animated\n var desiredScrollTop = this._computeScrollTopToRevealRange(this._context.viewLayout.getFutureViewport(), e.range, e.verticalType);\n // validate the new desired scroll top\n var newScrollPosition = this._context.viewLayout.validateScrollPosition({ scrollTop: desiredScrollTop });\n if (e.revealHorizontal) {\n if (e.range.startLineNumber !== e.range.endLineNumber) {\n // Two or more lines? => scroll to base (That's how you see most of the two lines)\n newScrollPosition = {\n scrollTop: newScrollPosition.scrollTop,\n scrollLeft: 0\n };\n }\n else {\n // We don't necessarily know the horizontal offset of this range since the line might not be in the view...\n this._horizontalRevealRequest = new HorizontalRevealRequest(e.range.startLineNumber, e.range.startColumn, e.range.endColumn, this._context.viewLayout.getCurrentScrollTop(), newScrollPosition.scrollTop, e.scrollType);\n }\n }\n else {\n this._horizontalRevealRequest = null;\n }\n var scrollTopDelta = Math.abs(this._context.viewLayout.getCurrentScrollTop() - newScrollPosition.scrollTop);\n if (e.scrollType === 0 /* Smooth */ && scrollTopDelta > this._lineHeight) {\n this._context.viewLayout.setScrollPositionSmooth(newScrollPosition);\n }\n else {\n this._context.viewLayout.setScrollPositionNow(newScrollPosition);\n }\n return true;\n };\n ViewLines.prototype.onScrollChanged = function (e) {\n if (this._horizontalRevealRequest && e.scrollLeftChanged) {\n // cancel any outstanding horizontal reveal request if someone else scrolls horizontally.\n this._horizontalRevealRequest = null;\n }\n if (this._horizontalRevealRequest && e.scrollTopChanged) {\n var min = Math.min(this._horizontalRevealRequest.startScrollTop, this._horizontalRevealRequest.stopScrollTop);\n var max = Math.max(this._horizontalRevealRequest.startScrollTop, this._horizontalRevealRequest.stopScrollTop);\n if (e.scrollTop < min || e.scrollTop > max) {\n // cancel any outstanding horizontal reveal request if someone else scrolls vertically.\n this._horizontalRevealRequest = null;\n }\n }\n this.domNode.setWidth(e.scrollWidth);\n return this._visibleLines.onScrollChanged(e) || true;\n };\n ViewLines.prototype.onTokensChanged = function (e) {\n return this._visibleLines.onTokensChanged(e);\n };\n ViewLines.prototype.onZonesChanged = function (e) {\n this._context.viewLayout.onMaxLineWidthChanged(this._maxLineWidth);\n return this._visibleLines.onZonesChanged(e);\n };\n ViewLines.prototype.onThemeChanged = function (e) {\n return this._onOptionsMaybeChanged();\n };\n // ---- end view event handlers\n // ----------- HELPERS FOR OTHERS\n ViewLines.prototype.getPositionFromDOMInfo = function (spanNode, offset) {\n var viewLineDomNode = this._getViewLineDomNode(spanNode);\n if (viewLineDomNode === null) {\n // Couldn't find view line node\n return null;\n }\n var lineNumber = this._getLineNumberFor(viewLineDomNode);\n if (lineNumber === -1) {\n // Couldn't find view line node\n return null;\n }\n if (lineNumber < 1 || lineNumber > this._context.model.getLineCount()) {\n // lineNumber is outside range\n return null;\n }\n if (this._context.model.getLineMaxColumn(lineNumber) === 1) {\n // Line is empty\n return new Position(lineNumber, 1);\n }\n var rendStartLineNumber = this._visibleLines.getStartLineNumber();\n var rendEndLineNumber = this._visibleLines.getEndLineNumber();\n if (lineNumber < rendStartLineNumber || lineNumber > rendEndLineNumber) {\n // Couldn't find line\n return null;\n }\n var column = this._visibleLines.getVisibleLine(lineNumber).getColumnOfNodeOffset(lineNumber, spanNode, offset);\n var minColumn = this._context.model.getLineMinColumn(lineNumber);\n if (column < minColumn) {\n column = minColumn;\n }\n return new Position(lineNumber, column);\n };\n ViewLines.prototype._getViewLineDomNode = function (node) {\n while (node && node.nodeType === 1) {\n if (node.className === ViewLine.CLASS_NAME) {\n return node;\n }\n node = node.parentElement;\n }\n return null;\n };\n /**\n * @returns the line number of this view line dom node.\n */\n ViewLines.prototype._getLineNumberFor = function (domNode) {\n var startLineNumber = this._visibleLines.getStartLineNumber();\n var endLineNumber = this._visibleLines.getEndLineNumber();\n for (var lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {\n var line = this._visibleLines.getVisibleLine(lineNumber);\n if (domNode === line.getDomNode()) {\n return lineNumber;\n }\n }\n return -1;\n };\n ViewLines.prototype.getLineWidth = function (lineNumber) {\n var rendStartLineNumber = this._visibleLines.getStartLineNumber();\n var rendEndLineNumber = this._visibleLines.getEndLineNumber();\n if (lineNumber < rendStartLineNumber || lineNumber > rendEndLineNumber) {\n // Couldn't find line\n return -1;\n }\n return this._visibleLines.getVisibleLine(lineNumber).getWidth();\n };\n ViewLines.prototype.linesVisibleRangesForRange = function (_range, includeNewLines) {\n if (this.shouldRender()) {\n // Cannot read from the DOM because it is dirty\n // i.e. the model & the dom are out of sync, so I'd be reading something stale\n return null;\n }\n var originalEndLineNumber = _range.endLineNumber;\n var range = Range.intersectRanges(_range, this._lastRenderedData.getCurrentVisibleRange());\n if (!range) {\n return null;\n }\n var visibleRanges = [], visibleRangesLen = 0;\n var domReadingContext = new DomReadingContext(this.domNode.domNode, this._textRangeRestingSpot);\n var nextLineModelLineNumber = 0;\n if (includeNewLines) {\n nextLineModelLineNumber = this._context.model.coordinatesConverter.convertViewPositionToModelPosition(new Position(range.startLineNumber, 1)).lineNumber;\n }\n var rendStartLineNumber = this._visibleLines.getStartLineNumber();\n var rendEndLineNumber = this._visibleLines.getEndLineNumber();\n for (var lineNumber = range.startLineNumber; lineNumber <= range.endLineNumber; lineNumber++) {\n if (lineNumber < rendStartLineNumber || lineNumber > rendEndLineNumber) {\n continue;\n }\n var startColumn = lineNumber === range.startLineNumber ? range.startColumn : 1;\n var endColumn = lineNumber === range.endLineNumber ? range.endColumn : this._context.model.getLineMaxColumn(lineNumber);\n var visibleRangesForLine = this._visibleLines.getVisibleLine(lineNumber).getVisibleRangesForRange(startColumn, endColumn, domReadingContext);\n if (!visibleRangesForLine || visibleRangesForLine.length === 0) {\n continue;\n }\n if (includeNewLines && lineNumber < originalEndLineNumber) {\n var currentLineModelLineNumber = nextLineModelLineNumber;\n nextLineModelLineNumber = this._context.model.coordinatesConverter.convertViewPositionToModelPosition(new Position(lineNumber + 1, 1)).lineNumber;\n if (currentLineModelLineNumber !== nextLineModelLineNumber) {\n visibleRangesForLine[visibleRangesForLine.length - 1].width += this._typicalHalfwidthCharacterWidth;\n }\n }\n visibleRanges[visibleRangesLen++] = new LineVisibleRanges(lineNumber, visibleRangesForLine);\n }\n if (visibleRangesLen === 0) {\n return null;\n }\n return visibleRanges;\n };\n ViewLines.prototype.visibleRangesForRange2 = function (_range) {\n if (this.shouldRender()) {\n // Cannot read from the DOM because it is dirty\n // i.e. the model & the dom are out of sync, so I'd be reading something stale\n return null;\n }\n var range = Range.intersectRanges(_range, this._lastRenderedData.getCurrentVisibleRange());\n if (!range) {\n return null;\n }\n var result = [];\n var domReadingContext = new DomReadingContext(this.domNode.domNode, this._textRangeRestingSpot);\n var rendStartLineNumber = this._visibleLines.getStartLineNumber();\n var rendEndLineNumber = this._visibleLines.getEndLineNumber();\n for (var lineNumber = range.startLineNumber; lineNumber <= range.endLineNumber; lineNumber++) {\n if (lineNumber < rendStartLineNumber || lineNumber > rendEndLineNumber) {\n continue;\n }\n var startColumn = lineNumber === range.startLineNumber ? range.startColumn : 1;\n var endColumn = lineNumber === range.endLineNumber ? range.endColumn : this._context.model.getLineMaxColumn(lineNumber);\n var visibleRangesForLine = this._visibleLines.getVisibleLine(lineNumber).getVisibleRangesForRange(startColumn, endColumn, domReadingContext);\n if (!visibleRangesForLine || visibleRangesForLine.length === 0) {\n continue;\n }\n result = result.concat(visibleRangesForLine);\n }\n if (result.length === 0) {\n return null;\n }\n return result;\n };\n ViewLines.prototype.visibleRangeForPosition = function (position) {\n var visibleRanges = this.visibleRangesForRange2(new Range(position.lineNumber, position.column, position.lineNumber, position.column));\n if (!visibleRanges) {\n return null;\n }\n return visibleRanges[0];\n };\n // --- implementation\n ViewLines.prototype.updateLineWidths = function () {\n this._updateLineWidths(false);\n };\n /**\n * Updates the max line width if it is fast to compute.\n * Returns true if all lines were taken into account.\n * Returns false if some lines need to be reevaluated (in a slow fashion).\n */\n ViewLines.prototype._updateLineWidthsFast = function () {\n return this._updateLineWidths(true);\n };\n ViewLines.prototype._updateLineWidthsSlow = function () {\n this._updateLineWidths(false);\n };\n ViewLines.prototype._updateLineWidths = function (fast) {\n var rendStartLineNumber = this._visibleLines.getStartLineNumber();\n var rendEndLineNumber = this._visibleLines.getEndLineNumber();\n var localMaxLineWidth = 1;\n var allWidthsComputed = true;\n for (var lineNumber = rendStartLineNumber; lineNumber <= rendEndLineNumber; lineNumber++) {\n var visibleLine = this._visibleLines.getVisibleLine(lineNumber);\n if (fast && !visibleLine.getWidthIsFast()) {\n // Cannot compute width in a fast way for this line\n allWidthsComputed = false;\n continue;\n }\n localMaxLineWidth = Math.max(localMaxLineWidth, visibleLine.getWidth());\n }\n if (allWidthsComputed && rendStartLineNumber === 1 && rendEndLineNumber === this._context.model.getLineCount()) {\n // we know the max line width for all the lines\n this._maxLineWidth = 0;\n }\n this._ensureMaxLineWidth(localMaxLineWidth);\n return allWidthsComputed;\n };\n ViewLines.prototype.prepareRender = function () {\n throw new Error('Not supported');\n };\n ViewLines.prototype.render = function () {\n throw new Error('Not supported');\n };\n ViewLines.prototype.renderText = function (viewportData) {\n // (1) render lines - ensures lines are in the DOM\n this._visibleLines.renderLines(viewportData);\n this._lastRenderedData.setCurrentVisibleRange(viewportData.visibleRange);\n this.domNode.setWidth(this._context.viewLayout.getScrollWidth());\n this.domNode.setHeight(Math.min(this._context.viewLayout.getScrollHeight(), 1000000));\n // (2) compute horizontal scroll position:\n // - this must happen after the lines are in the DOM since it might need a line that rendered just now\n // - it might change `scrollWidth` and `scrollLeft`\n if (this._horizontalRevealRequest) {\n var revealLineNumber = this._horizontalRevealRequest.lineNumber;\n var revealStartColumn = this._horizontalRevealRequest.startColumn;\n var revealEndColumn = this._horizontalRevealRequest.endColumn;\n var scrollType = this._horizontalRevealRequest.scrollType;\n // Check that we have the line that contains the horizontal range in the viewport\n if (viewportData.startLineNumber <= revealLineNumber && revealLineNumber <= viewportData.endLineNumber) {\n this._horizontalRevealRequest = null;\n // allow `visibleRangesForRange2` to work\n this.onDidRender();\n // compute new scroll position\n var newScrollLeft = this._computeScrollLeftToRevealRange(revealLineNumber, revealStartColumn, revealEndColumn);\n var isViewportWrapping = this._isViewportWrapping;\n if (!isViewportWrapping) {\n // ensure `scrollWidth` is large enough\n this._ensureMaxLineWidth(newScrollLeft.maxHorizontalOffset);\n }\n // set `scrollLeft`\n if (scrollType === 0 /* Smooth */) {\n this._context.viewLayout.setScrollPositionSmooth({\n scrollLeft: newScrollLeft.scrollLeft\n });\n }\n else {\n this._context.viewLayout.setScrollPositionNow({\n scrollLeft: newScrollLeft.scrollLeft\n });\n }\n }\n }\n // Update max line width (not so important, it is just so the horizontal scrollbar doesn't get too small)\n if (!this._updateLineWidthsFast()) {\n // Computing the width of some lines would be slow => delay it\n this._asyncUpdateLineWidths.schedule();\n }\n // (3) handle scrolling\n this._linesContent.setLayerHinting(this._canUseLayerHinting);\n var adjustedScrollTop = this._context.viewLayout.getCurrentScrollTop() - viewportData.bigNumbersDelta;\n this._linesContent.setTop(-adjustedScrollTop);\n this._linesContent.setLeft(-this._context.viewLayout.getCurrentScrollLeft());\n };\n // --- width\n ViewLines.prototype._ensureMaxLineWidth = function (lineWidth) {\n var iLineWidth = Math.ceil(lineWidth);\n if (this._maxLineWidth < iLineWidth) {\n this._maxLineWidth = iLineWidth;\n this._context.viewLayout.onMaxLineWidthChanged(this._maxLineWidth);\n }\n };\n ViewLines.prototype._computeScrollTopToRevealRange = function (viewport, range, verticalType) {\n var viewportStartY = viewport.top;\n var viewportHeight = viewport.height;\n var viewportEndY = viewportStartY + viewportHeight;\n var boxStartY;\n var boxEndY;\n // Have a box that includes one extra line height (for the horizontal scrollbar)\n boxStartY = this._context.viewLayout.getVerticalOffsetForLineNumber(range.startLineNumber);\n boxEndY = this._context.viewLayout.getVerticalOffsetForLineNumber(range.endLineNumber) + this._lineHeight;\n if (verticalType === 0 /* Simple */ || verticalType === 4 /* Bottom */) {\n // Reveal one line more when the last line would be covered by the scrollbar - arrow down case or revealing a line explicitly at bottom\n boxEndY += this._lineHeight;\n }\n var newScrollTop;\n if (verticalType === 1 /* Center */ || verticalType === 2 /* CenterIfOutsideViewport */) {\n if (verticalType === 2 /* CenterIfOutsideViewport */ && viewportStartY <= boxStartY && boxEndY <= viewportEndY) {\n // Box is already in the viewport... do nothing\n newScrollTop = viewportStartY;\n }\n else {\n // Box is outside the viewport... center it\n var boxMiddleY = (boxStartY + boxEndY) / 2;\n newScrollTop = Math.max(0, boxMiddleY - viewportHeight / 2);\n }\n }\n else {\n newScrollTop = this._computeMinimumScrolling(viewportStartY, viewportEndY, boxStartY, boxEndY, verticalType === 3 /* Top */, verticalType === 4 /* Bottom */);\n }\n return newScrollTop;\n };\n ViewLines.prototype._computeScrollLeftToRevealRange = function (lineNumber, startColumn, endColumn) {\n var maxHorizontalOffset = 0;\n var viewport = this._context.viewLayout.getCurrentViewport();\n var viewportStartX = viewport.left;\n var viewportEndX = viewportStartX + viewport.width;\n var visibleRanges = this.visibleRangesForRange2(new Range(lineNumber, startColumn, lineNumber, endColumn));\n var boxStartX = Number.MAX_VALUE;\n var boxEndX = 0;\n if (!visibleRanges) {\n // Unknown\n return {\n scrollLeft: viewportStartX,\n maxHorizontalOffset: maxHorizontalOffset\n };\n }\n for (var _i = 0, visibleRanges_1 = visibleRanges; _i < visibleRanges_1.length; _i++) {\n var visibleRange = visibleRanges_1[_i];\n if (visibleRange.left < boxStartX) {\n boxStartX = visibleRange.left;\n }\n if (visibleRange.left + visibleRange.width > boxEndX) {\n boxEndX = visibleRange.left + visibleRange.width;\n }\n }\n maxHorizontalOffset = boxEndX;\n boxStartX = Math.max(0, boxStartX - ViewLines.HORIZONTAL_EXTRA_PX);\n boxEndX += this._revealHorizontalRightPadding;\n var newScrollLeft = this._computeMinimumScrolling(viewportStartX, viewportEndX, boxStartX, boxEndX);\n return {\n scrollLeft: newScrollLeft,\n maxHorizontalOffset: maxHorizontalOffset\n };\n };\n ViewLines.prototype._computeMinimumScrolling = function (viewportStart, viewportEnd, boxStart, boxEnd, revealAtStart, revealAtEnd) {\n viewportStart = viewportStart | 0;\n viewportEnd = viewportEnd | 0;\n boxStart = boxStart | 0;\n boxEnd = boxEnd | 0;\n revealAtStart = !!revealAtStart;\n revealAtEnd = !!revealAtEnd;\n var viewportLength = viewportEnd - viewportStart;\n var boxLength = boxEnd - boxStart;\n if (boxLength < viewportLength) {\n // The box would fit in the viewport\n if (revealAtStart) {\n return boxStart;\n }\n if (revealAtEnd) {\n return Math.max(0, boxEnd - viewportLength);\n }\n if (boxStart < viewportStart) {\n // The box is above the viewport\n return boxStart;\n }\n else if (boxEnd > viewportEnd) {\n // The box is below the viewport\n return Math.max(0, boxEnd - viewportLength);\n }\n }\n else {\n // The box would not fit in the viewport\n // Reveal the beginning of the box\n return boxStart;\n }\n return viewportStart;\n };\n /**\n * Adds this amount of pixels to the right of lines (no-one wants to type near the edge of the viewport)\n */\n ViewLines.HORIZONTAL_EXTRA_PX = 30;\n return ViewLines;\n}(ViewPart));\nexport { ViewLines };\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport './linesDecorations.css';\nimport { DecorationToRender, DedupOverlay } from '../glyphMargin/glyphMargin.js';\nvar LinesDecorationsOverlay = /** @class */ (function (_super) {\n __extends(LinesDecorationsOverlay, _super);\n function LinesDecorationsOverlay(context) {\n var _this = _super.call(this) || this;\n _this._context = context;\n _this._decorationsLeft = _this._context.configuration.editor.layoutInfo.decorationsLeft;\n _this._decorationsWidth = _this._context.configuration.editor.layoutInfo.decorationsWidth;\n _this._renderResult = null;\n _this._context.addEventHandler(_this);\n return _this;\n }\n LinesDecorationsOverlay.prototype.dispose = function () {\n this._context.removeEventHandler(this);\n this._renderResult = null;\n _super.prototype.dispose.call(this);\n };\n // --- begin event handlers\n LinesDecorationsOverlay.prototype.onConfigurationChanged = function (e) {\n if (e.layoutInfo) {\n this._decorationsLeft = this._context.configuration.editor.layoutInfo.decorationsLeft;\n this._decorationsWidth = this._context.configuration.editor.layoutInfo.decorationsWidth;\n }\n return true;\n };\n LinesDecorationsOverlay.prototype.onDecorationsChanged = function (e) {\n return true;\n };\n LinesDecorationsOverlay.prototype.onFlushed = function (e) {\n return true;\n };\n LinesDecorationsOverlay.prototype.onLinesChanged = function (e) {\n return true;\n };\n LinesDecorationsOverlay.prototype.onLinesDeleted = function (e) {\n return true;\n };\n LinesDecorationsOverlay.prototype.onLinesInserted = function (e) {\n return true;\n };\n LinesDecorationsOverlay.prototype.onScrollChanged = function (e) {\n return e.scrollTopChanged;\n };\n LinesDecorationsOverlay.prototype.onZonesChanged = function (e) {\n return true;\n };\n // --- end event handlers\n LinesDecorationsOverlay.prototype._getDecorations = function (ctx) {\n var decorations = ctx.getDecorationsInViewport();\n var r = [], rLen = 0;\n for (var i = 0, len = decorations.length; i < len; i++) {\n var d = decorations[i];\n var linesDecorationsClassName = d.options.linesDecorationsClassName;\n if (linesDecorationsClassName) {\n r[rLen++] = new DecorationToRender(d.range.startLineNumber, d.range.endLineNumber, linesDecorationsClassName);\n }\n }\n return r;\n };\n LinesDecorationsOverlay.prototype.prepareRender = function (ctx) {\n var visibleStartLineNumber = ctx.visibleRange.startLineNumber;\n var visibleEndLineNumber = ctx.visibleRange.endLineNumber;\n var toRender = this._render(visibleStartLineNumber, visibleEndLineNumber, this._getDecorations(ctx));\n var left = this._decorationsLeft.toString();\n var width = this._decorationsWidth.toString();\n var common = '\" style=\"left:' + left + 'px;width:' + width + 'px;\">
';\n var output = [];\n for (var lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {\n var lineIndex = lineNumber - visibleStartLineNumber;\n var classNames = toRender[lineIndex];\n var lineOutput = '';\n for (var i = 0, len = classNames.length; i < len; i++) {\n lineOutput += '\";\n var charIndex = startOffset;\n var tabsCharDelta = 0;\n for (var tokenIndex = 0, tokenCount = viewLineTokens.getCount(); tokenIndex < tokenCount; tokenIndex++) {\n var tokenEndIndex = viewLineTokens.getEndOffset(tokenIndex);\n if (tokenEndIndex <= startOffset) {\n continue;\n }\n var partContent = '';\n for (; charIndex < tokenEndIndex && charIndex < endOffset; charIndex++) {\n var charCode = text.charCodeAt(charIndex);\n switch (charCode) {\n case 9 /* Tab */:\n var insertSpacesCount = tabSize - (charIndex + tabsCharDelta) % tabSize;\n tabsCharDelta += insertSpacesCount - 1;\n while (insertSpacesCount > 0) {\n partContent += ' ';\n insertSpacesCount--;\n }\n break;\n case 60 /* LessThan */:\n partContent += '<';\n break;\n case 62 /* GreaterThan */:\n partContent += '>';\n break;\n case 38 /* Ampersand */:\n partContent += '&';\n break;\n case 0 /* Null */:\n partContent += '';\n break;\n case 65279 /* UTF8_BOM */:\n case 8232 /* LINE_SEPARATOR_2028 */:\n partContent += '\\ufffd';\n break;\n case 13 /* CarriageReturn */:\n // zero width space, because carriage return would introduce a line break\n partContent += '';\n break;\n default:\n partContent += String.fromCharCode(charCode);\n }\n }\n result += \"\" + partContent + \"\";\n if (tokenEndIndex > endOffset || charIndex >= endOffset) {\n break;\n }\n }\n result += \"
\";\n return result;\n}\nfunction _tokenizeToString(text, tokenizationSupport) {\n var result = \"\";\n var lines = text.split(/\\r\\n|\\r|\\n/);\n var currentState = tokenizationSupport.getInitialState();\n for (var i = 0, len = lines.length; i < len; i++) {\n var line = lines[i];\n if (i > 0) {\n result += \"
\";\n }\n var tokenizationResult = tokenizationSupport.tokenize2(line, currentState, 0);\n LineTokens.convertToEndOffset(tokenizationResult.tokens, line.length);\n var lineTokens = new LineTokens(tokenizationResult.tokens, line);\n var viewLineTokens = lineTokens.inflate();\n var startOffset = 0;\n for (var j = 0, lenJ = viewLineTokens.getCount(); j < lenJ; j++) {\n var type = viewLineTokens.getClassName(j);\n var endIndex = viewLineTokens.getEndOffset(j);\n result += \"\" + strings.escape(line.substring(startOffset, endIndex)) + \"\";\n startOffset = endIndex;\n }\n currentState = tokenizationResult.endState;\n }\n result += \"
\";\n return result;\n}\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n/**\n * Represent whitespaces in between lines and provide fast CRUD management methods.\n * The whitespaces are sorted ascending by `afterLineNumber`.\n */\nvar WhitespaceComputer = /** @class */ (function () {\n function WhitespaceComputer() {\n this._heights = [];\n this._minWidths = [];\n this._ids = [];\n this._afterLineNumbers = [];\n this._ordinals = [];\n this._prefixSum = [];\n this._prefixSumValidIndex = -1;\n this._whitespaceId2Index = {};\n this._lastWhitespaceId = 0;\n this._minWidth = -1; /* marker for not being computed */\n }\n /**\n * Find the insertion index for a new value inside a sorted array of values.\n * If the value is already present in the sorted array, the insertion index will be after the already existing value.\n */\n WhitespaceComputer.findInsertionIndex = function (sortedArray, value, ordinals, valueOrdinal) {\n var low = 0;\n var high = sortedArray.length;\n while (low < high) {\n var mid = ((low + high) >>> 1);\n if (value === sortedArray[mid]) {\n if (valueOrdinal < ordinals[mid]) {\n high = mid;\n }\n else {\n low = mid + 1;\n }\n }\n else if (value < sortedArray[mid]) {\n high = mid;\n }\n else {\n low = mid + 1;\n }\n }\n return low;\n };\n /**\n * Insert a new whitespace of a certain height after a line number.\n * The whitespace has a \"sticky\" characteristic.\n * Irrespective of edits above or below `afterLineNumber`, the whitespace will follow the initial line.\n *\n * @param afterLineNumber The conceptual position of this whitespace. The whitespace will follow this line as best as possible even when deleting/inserting lines above/below.\n * @param heightInPx The height of the whitespace, in pixels.\n * @return An id that can be used later to mutate or delete the whitespace\n */\n WhitespaceComputer.prototype.insertWhitespace = function (afterLineNumber, ordinal, heightInPx, minWidth) {\n afterLineNumber = afterLineNumber | 0;\n ordinal = ordinal | 0;\n heightInPx = heightInPx | 0;\n minWidth = minWidth | 0;\n var id = (++this._lastWhitespaceId);\n var insertionIndex = WhitespaceComputer.findInsertionIndex(this._afterLineNumbers, afterLineNumber, this._ordinals, ordinal);\n this._insertWhitespaceAtIndex(id, insertionIndex, afterLineNumber, ordinal, heightInPx, minWidth);\n this._minWidth = -1; /* marker for not being computed */\n return id;\n };\n WhitespaceComputer.prototype._insertWhitespaceAtIndex = function (id, insertIndex, afterLineNumber, ordinal, heightInPx, minWidth) {\n id = id | 0;\n insertIndex = insertIndex | 0;\n afterLineNumber = afterLineNumber | 0;\n ordinal = ordinal | 0;\n heightInPx = heightInPx | 0;\n minWidth = minWidth | 0;\n this._heights.splice(insertIndex, 0, heightInPx);\n this._minWidths.splice(insertIndex, 0, minWidth);\n this._ids.splice(insertIndex, 0, id);\n this._afterLineNumbers.splice(insertIndex, 0, afterLineNumber);\n this._ordinals.splice(insertIndex, 0, ordinal);\n this._prefixSum.splice(insertIndex, 0, 0);\n var keys = Object.keys(this._whitespaceId2Index);\n for (var i = 0, len = keys.length; i < len; i++) {\n var sid = keys[i];\n var oldIndex = this._whitespaceId2Index[sid];\n if (oldIndex >= insertIndex) {\n this._whitespaceId2Index[sid] = oldIndex + 1;\n }\n }\n this._whitespaceId2Index[id.toString()] = insertIndex;\n this._prefixSumValidIndex = Math.min(this._prefixSumValidIndex, insertIndex - 1);\n };\n /**\n * Change properties associated with a certain whitespace.\n */\n WhitespaceComputer.prototype.changeWhitespace = function (id, newAfterLineNumber, newHeight) {\n id = id | 0;\n newAfterLineNumber = newAfterLineNumber | 0;\n newHeight = newHeight | 0;\n var hasChanges = false;\n hasChanges = this.changeWhitespaceHeight(id, newHeight) || hasChanges;\n hasChanges = this.changeWhitespaceAfterLineNumber(id, newAfterLineNumber) || hasChanges;\n return hasChanges;\n };\n /**\n * Change the height of an existing whitespace\n *\n * @param id The whitespace to change\n * @param newHeightInPx The new height of the whitespace, in pixels\n * @return Returns true if the whitespace is found and if the new height is different than the old height\n */\n WhitespaceComputer.prototype.changeWhitespaceHeight = function (id, newHeightInPx) {\n id = id | 0;\n newHeightInPx = newHeightInPx | 0;\n var sid = id.toString();\n if (this._whitespaceId2Index.hasOwnProperty(sid)) {\n var index = this._whitespaceId2Index[sid];\n if (this._heights[index] !== newHeightInPx) {\n this._heights[index] = newHeightInPx;\n this._prefixSumValidIndex = Math.min(this._prefixSumValidIndex, index - 1);\n return true;\n }\n }\n return false;\n };\n /**\n * Change the line number after which an existing whitespace flows.\n *\n * @param id The whitespace to change\n * @param newAfterLineNumber The new line number the whitespace will follow\n * @return Returns true if the whitespace is found and if the new line number is different than the old line number\n */\n WhitespaceComputer.prototype.changeWhitespaceAfterLineNumber = function (id, newAfterLineNumber) {\n id = id | 0;\n newAfterLineNumber = newAfterLineNumber | 0;\n var sid = id.toString();\n if (this._whitespaceId2Index.hasOwnProperty(sid)) {\n var index = this._whitespaceId2Index[sid];\n if (this._afterLineNumbers[index] !== newAfterLineNumber) {\n // `afterLineNumber` changed for this whitespace\n // Record old ordinal\n var ordinal = this._ordinals[index];\n // Record old height\n var heightInPx = this._heights[index];\n // Record old min width\n var minWidth = this._minWidths[index];\n // Since changing `afterLineNumber` can trigger a reordering, we're gonna remove this whitespace\n this.removeWhitespace(id);\n // And add it again\n var insertionIndex = WhitespaceComputer.findInsertionIndex(this._afterLineNumbers, newAfterLineNumber, this._ordinals, ordinal);\n this._insertWhitespaceAtIndex(id, insertionIndex, newAfterLineNumber, ordinal, heightInPx, minWidth);\n return true;\n }\n }\n return false;\n };\n /**\n * Remove an existing whitespace.\n *\n * @param id The whitespace to remove\n * @return Returns true if the whitespace is found and it is removed.\n */\n WhitespaceComputer.prototype.removeWhitespace = function (id) {\n id = id | 0;\n var sid = id.toString();\n if (this._whitespaceId2Index.hasOwnProperty(sid)) {\n var index = this._whitespaceId2Index[sid];\n delete this._whitespaceId2Index[sid];\n this._removeWhitespaceAtIndex(index);\n this._minWidth = -1; /* marker for not being computed */\n return true;\n }\n return false;\n };\n WhitespaceComputer.prototype._removeWhitespaceAtIndex = function (removeIndex) {\n removeIndex = removeIndex | 0;\n this._heights.splice(removeIndex, 1);\n this._minWidths.splice(removeIndex, 1);\n this._ids.splice(removeIndex, 1);\n this._afterLineNumbers.splice(removeIndex, 1);\n this._ordinals.splice(removeIndex, 1);\n this._prefixSum.splice(removeIndex, 1);\n this._prefixSumValidIndex = Math.min(this._prefixSumValidIndex, removeIndex - 1);\n var keys = Object.keys(this._whitespaceId2Index);\n for (var i = 0, len = keys.length; i < len; i++) {\n var sid = keys[i];\n var oldIndex = this._whitespaceId2Index[sid];\n if (oldIndex >= removeIndex) {\n this._whitespaceId2Index[sid] = oldIndex - 1;\n }\n }\n };\n /**\n * Notify the computer that lines have been deleted (a continuous zone of lines).\n * This gives it a chance to update `afterLineNumber` for whitespaces, giving the \"sticky\" characteristic.\n *\n * @param fromLineNumber The line number at which the deletion started, inclusive\n * @param toLineNumber The line number at which the deletion ended, inclusive\n */\n WhitespaceComputer.prototype.onLinesDeleted = function (fromLineNumber, toLineNumber) {\n fromLineNumber = fromLineNumber | 0;\n toLineNumber = toLineNumber | 0;\n for (var i = 0, len = this._afterLineNumbers.length; i < len; i++) {\n var afterLineNumber = this._afterLineNumbers[i];\n if (fromLineNumber <= afterLineNumber && afterLineNumber <= toLineNumber) {\n // The line this whitespace was after has been deleted\n // => move whitespace to before first deleted line\n this._afterLineNumbers[i] = fromLineNumber - 1;\n }\n else if (afterLineNumber > toLineNumber) {\n // The line this whitespace was after has been moved up\n // => move whitespace up\n this._afterLineNumbers[i] -= (toLineNumber - fromLineNumber + 1);\n }\n }\n };\n /**\n * Notify the computer that lines have been inserted (a continuous zone of lines).\n * This gives it a chance to update `afterLineNumber` for whitespaces, giving the \"sticky\" characteristic.\n *\n * @param fromLineNumber The line number at which the insertion started, inclusive\n * @param toLineNumber The line number at which the insertion ended, inclusive.\n */\n WhitespaceComputer.prototype.onLinesInserted = function (fromLineNumber, toLineNumber) {\n fromLineNumber = fromLineNumber | 0;\n toLineNumber = toLineNumber | 0;\n for (var i = 0, len = this._afterLineNumbers.length; i < len; i++) {\n var afterLineNumber = this._afterLineNumbers[i];\n if (fromLineNumber <= afterLineNumber) {\n this._afterLineNumbers[i] += (toLineNumber - fromLineNumber + 1);\n }\n }\n };\n /**\n * Get the sum of all the whitespaces.\n */\n WhitespaceComputer.prototype.getTotalHeight = function () {\n if (this._heights.length === 0) {\n return 0;\n }\n return this.getAccumulatedHeight(this._heights.length - 1);\n };\n /**\n * Return the sum of the heights of the whitespaces at [0..index].\n * This includes the whitespace at `index`.\n *\n * @param index The index of the whitespace.\n * @return The sum of the heights of all whitespaces before the one at `index`, including the one at `index`.\n */\n WhitespaceComputer.prototype.getAccumulatedHeight = function (index) {\n index = index | 0;\n var startIndex = Math.max(0, this._prefixSumValidIndex + 1);\n if (startIndex === 0) {\n this._prefixSum[0] = this._heights[0];\n startIndex++;\n }\n for (var i = startIndex; i <= index; i++) {\n this._prefixSum[i] = this._prefixSum[i - 1] + this._heights[i];\n }\n this._prefixSumValidIndex = Math.max(this._prefixSumValidIndex, index);\n return this._prefixSum[index];\n };\n /**\n * Find all whitespaces with `afterLineNumber` < `lineNumber` and return the sum of their heights.\n *\n * @param lineNumber The line number whitespaces should be before.\n * @return The sum of the heights of the whitespaces before `lineNumber`.\n */\n WhitespaceComputer.prototype.getAccumulatedHeightBeforeLineNumber = function (lineNumber) {\n lineNumber = lineNumber | 0;\n var lastWhitespaceBeforeLineNumber = this._findLastWhitespaceBeforeLineNumber(lineNumber);\n if (lastWhitespaceBeforeLineNumber === -1) {\n return 0;\n }\n return this.getAccumulatedHeight(lastWhitespaceBeforeLineNumber);\n };\n WhitespaceComputer.prototype._findLastWhitespaceBeforeLineNumber = function (lineNumber) {\n lineNumber = lineNumber | 0;\n // Find the whitespace before line number\n var afterLineNumbers = this._afterLineNumbers;\n var low = 0;\n var high = afterLineNumbers.length - 1;\n while (low <= high) {\n var delta = (high - low) | 0;\n var halfDelta = (delta / 2) | 0;\n var mid = (low + halfDelta) | 0;\n if (afterLineNumbers[mid] < lineNumber) {\n if (mid + 1 >= afterLineNumbers.length || afterLineNumbers[mid + 1] >= lineNumber) {\n return mid;\n }\n else {\n low = (mid + 1) | 0;\n }\n }\n else {\n high = (mid - 1) | 0;\n }\n }\n return -1;\n };\n WhitespaceComputer.prototype._findFirstWhitespaceAfterLineNumber = function (lineNumber) {\n lineNumber = lineNumber | 0;\n var lastWhitespaceBeforeLineNumber = this._findLastWhitespaceBeforeLineNumber(lineNumber);\n var firstWhitespaceAfterLineNumber = lastWhitespaceBeforeLineNumber + 1;\n if (firstWhitespaceAfterLineNumber < this._heights.length) {\n return firstWhitespaceAfterLineNumber;\n }\n return -1;\n };\n /**\n * Find the index of the first whitespace which has `afterLineNumber` >= `lineNumber`.\n * @return The index of the first whitespace with `afterLineNumber` >= `lineNumber` or -1 if no whitespace is found.\n */\n WhitespaceComputer.prototype.getFirstWhitespaceIndexAfterLineNumber = function (lineNumber) {\n lineNumber = lineNumber | 0;\n return this._findFirstWhitespaceAfterLineNumber(lineNumber);\n };\n /**\n * The number of whitespaces.\n */\n WhitespaceComputer.prototype.getCount = function () {\n return this._heights.length;\n };\n /**\n * The maximum min width for all whitespaces.\n */\n WhitespaceComputer.prototype.getMinWidth = function () {\n if (this._minWidth === -1) {\n var minWidth = 0;\n for (var i = 0, len = this._minWidths.length; i < len; i++) {\n minWidth = Math.max(minWidth, this._minWidths[i]);\n }\n this._minWidth = minWidth;\n }\n return this._minWidth;\n };\n /**\n * Get the `afterLineNumber` for whitespace at index `index`.\n *\n * @param index The index of the whitespace.\n * @return `afterLineNumber` of whitespace at `index`.\n */\n WhitespaceComputer.prototype.getAfterLineNumberForWhitespaceIndex = function (index) {\n index = index | 0;\n return this._afterLineNumbers[index];\n };\n /**\n * Get the `id` for whitespace at index `index`.\n *\n * @param index The index of the whitespace.\n * @return `id` of whitespace at `index`.\n */\n WhitespaceComputer.prototype.getIdForWhitespaceIndex = function (index) {\n index = index | 0;\n return this._ids[index];\n };\n /**\n * Get the `height` for whitespace at index `index`.\n *\n * @param index The index of the whitespace.\n * @return `height` of whitespace at `index`.\n */\n WhitespaceComputer.prototype.getHeightForWhitespaceIndex = function (index) {\n index = index | 0;\n return this._heights[index];\n };\n /**\n * Get all whitespaces.\n */\n WhitespaceComputer.prototype.getWhitespaces = function (deviceLineHeight) {\n deviceLineHeight = deviceLineHeight | 0;\n var result = [];\n for (var i = 0; i < this._heights.length; i++) {\n result.push({\n id: this._ids[i],\n afterLineNumber: this._afterLineNumbers[i],\n heightInLines: this._heights[i] / deviceLineHeight\n });\n }\n return result;\n };\n return WhitespaceComputer;\n}());\nexport { WhitespaceComputer };\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport { WhitespaceComputer } from './whitespaceComputer.js';\n/**\n * Layouting of objects that take vertical space (by having a height) and push down other objects.\n *\n * These objects are basically either text (lines) or spaces between those lines (whitespaces).\n * This provides commodity operations for working with lines that contain whitespace that pushes lines lower (vertically).\n * This is written with no knowledge of an editor in mind.\n */\nvar LinesLayout = /** @class */ (function () {\n function LinesLayout(lineCount, lineHeight) {\n this._lineCount = lineCount;\n this._lineHeight = lineHeight;\n this._whitespaces = new WhitespaceComputer();\n }\n /**\n * Change the height of a line in pixels.\n */\n LinesLayout.prototype.setLineHeight = function (lineHeight) {\n this._lineHeight = lineHeight;\n };\n /**\n * Set the number of lines.\n *\n * @param lineCount New number of lines.\n */\n LinesLayout.prototype.onFlushed = function (lineCount) {\n this._lineCount = lineCount;\n };\n /**\n * Insert a new whitespace of a certain height after a line number.\n * The whitespace has a \"sticky\" characteristic.\n * Irrespective of edits above or below `afterLineNumber`, the whitespace will follow the initial line.\n *\n * @param afterLineNumber The conceptual position of this whitespace. The whitespace will follow this line as best as possible even when deleting/inserting lines above/below.\n * @param heightInPx The height of the whitespace, in pixels.\n * @return An id that can be used later to mutate or delete the whitespace\n */\n LinesLayout.prototype.insertWhitespace = function (afterLineNumber, ordinal, heightInPx, minWidth) {\n return this._whitespaces.insertWhitespace(afterLineNumber, ordinal, heightInPx, minWidth);\n };\n /**\n * Change properties associated with a certain whitespace.\n */\n LinesLayout.prototype.changeWhitespace = function (id, newAfterLineNumber, newHeight) {\n return this._whitespaces.changeWhitespace(id, newAfterLineNumber, newHeight);\n };\n /**\n * Remove an existing whitespace.\n *\n * @param id The whitespace to remove\n * @return Returns true if the whitespace is found and it is removed.\n */\n LinesLayout.prototype.removeWhitespace = function (id) {\n return this._whitespaces.removeWhitespace(id);\n };\n /**\n * Notify the layouter that lines have been deleted (a continuous zone of lines).\n *\n * @param fromLineNumber The line number at which the deletion started, inclusive\n * @param toLineNumber The line number at which the deletion ended, inclusive\n */\n LinesLayout.prototype.onLinesDeleted = function (fromLineNumber, toLineNumber) {\n this._lineCount -= (toLineNumber - fromLineNumber + 1);\n this._whitespaces.onLinesDeleted(fromLineNumber, toLineNumber);\n };\n /**\n * Notify the layouter that lines have been inserted (a continuous zone of lines).\n *\n * @param fromLineNumber The line number at which the insertion started, inclusive\n * @param toLineNumber The line number at which the insertion ended, inclusive.\n */\n LinesLayout.prototype.onLinesInserted = function (fromLineNumber, toLineNumber) {\n this._lineCount += (toLineNumber - fromLineNumber + 1);\n this._whitespaces.onLinesInserted(fromLineNumber, toLineNumber);\n };\n /**\n * Get the sum of heights for all objects.\n *\n * @return The sum of heights for all objects.\n */\n LinesLayout.prototype.getLinesTotalHeight = function () {\n var linesHeight = this._lineHeight * this._lineCount;\n var whitespacesHeight = this._whitespaces.getTotalHeight();\n return linesHeight + whitespacesHeight;\n };\n /**\n * Get the vertical offset (the sum of heights for all objects above) a certain line number.\n *\n * @param lineNumber The line number\n * @return The sum of heights for all objects above `lineNumber`.\n */\n LinesLayout.prototype.getVerticalOffsetForLineNumber = function (lineNumber) {\n lineNumber = lineNumber | 0;\n var previousLinesHeight;\n if (lineNumber > 1) {\n previousLinesHeight = this._lineHeight * (lineNumber - 1);\n }\n else {\n previousLinesHeight = 0;\n }\n var previousWhitespacesHeight = this._whitespaces.getAccumulatedHeightBeforeLineNumber(lineNumber);\n return previousLinesHeight + previousWhitespacesHeight;\n };\n /**\n * Returns the accumulated height of whitespaces before the given line number.\n *\n * @param lineNumber The line number\n */\n LinesLayout.prototype.getWhitespaceAccumulatedHeightBeforeLineNumber = function (lineNumber) {\n return this._whitespaces.getAccumulatedHeightBeforeLineNumber(lineNumber);\n };\n LinesLayout.prototype.getWhitespaceMinWidth = function () {\n return this._whitespaces.getMinWidth();\n };\n /**\n * Check if `verticalOffset` is below all lines.\n */\n LinesLayout.prototype.isAfterLines = function (verticalOffset) {\n var totalHeight = this.getLinesTotalHeight();\n return verticalOffset > totalHeight;\n };\n /**\n * Find the first line number that is at or after vertical offset `verticalOffset`.\n * i.e. if getVerticalOffsetForLine(line) is x and getVerticalOffsetForLine(line + 1) is y, then\n * getLineNumberAtOrAfterVerticalOffset(i) = line, x <= i < y.\n *\n * @param verticalOffset The vertical offset to search at.\n * @return The line number at or after vertical offset `verticalOffset`.\n */\n LinesLayout.prototype.getLineNumberAtOrAfterVerticalOffset = function (verticalOffset) {\n verticalOffset = verticalOffset | 0;\n if (verticalOffset < 0) {\n return 1;\n }\n var linesCount = this._lineCount | 0;\n var lineHeight = this._lineHeight;\n var minLineNumber = 1;\n var maxLineNumber = linesCount;\n while (minLineNumber < maxLineNumber) {\n var midLineNumber = ((minLineNumber + maxLineNumber) / 2) | 0;\n var midLineNumberVerticalOffset = this.getVerticalOffsetForLineNumber(midLineNumber) | 0;\n if (verticalOffset >= midLineNumberVerticalOffset + lineHeight) {\n // vertical offset is after mid line number\n minLineNumber = midLineNumber + 1;\n }\n else if (verticalOffset >= midLineNumberVerticalOffset) {\n // Hit\n return midLineNumber;\n }\n else {\n // vertical offset is before mid line number, but mid line number could still be what we're searching for\n maxLineNumber = midLineNumber;\n }\n }\n if (minLineNumber > linesCount) {\n return linesCount;\n }\n return minLineNumber;\n };\n /**\n * Get all the lines and their relative vertical offsets that are positioned between `verticalOffset1` and `verticalOffset2`.\n *\n * @param verticalOffset1 The beginning of the viewport.\n * @param verticalOffset2 The end of the viewport.\n * @return A structure describing the lines positioned between `verticalOffset1` and `verticalOffset2`.\n */\n LinesLayout.prototype.getLinesViewportData = function (verticalOffset1, verticalOffset2) {\n verticalOffset1 = verticalOffset1 | 0;\n verticalOffset2 = verticalOffset2 | 0;\n var lineHeight = this._lineHeight;\n // Find first line number\n // We don't live in a perfect world, so the line number might start before or after verticalOffset1\n var startLineNumber = this.getLineNumberAtOrAfterVerticalOffset(verticalOffset1) | 0;\n var startLineNumberVerticalOffset = this.getVerticalOffsetForLineNumber(startLineNumber) | 0;\n var endLineNumber = this._lineCount | 0;\n // Also keep track of what whitespace we've got\n var whitespaceIndex = this._whitespaces.getFirstWhitespaceIndexAfterLineNumber(startLineNumber) | 0;\n var whitespaceCount = this._whitespaces.getCount() | 0;\n var currentWhitespaceHeight;\n var currentWhitespaceAfterLineNumber;\n if (whitespaceIndex === -1) {\n whitespaceIndex = whitespaceCount;\n currentWhitespaceAfterLineNumber = endLineNumber + 1;\n currentWhitespaceHeight = 0;\n }\n else {\n currentWhitespaceAfterLineNumber = this._whitespaces.getAfterLineNumberForWhitespaceIndex(whitespaceIndex) | 0;\n currentWhitespaceHeight = this._whitespaces.getHeightForWhitespaceIndex(whitespaceIndex) | 0;\n }\n var currentVerticalOffset = startLineNumberVerticalOffset;\n var currentLineRelativeOffset = currentVerticalOffset;\n // IE (all versions) cannot handle units above about 1,533,908 px, so every 500k pixels bring numbers down\n var STEP_SIZE = 500000;\n var bigNumbersDelta = 0;\n if (startLineNumberVerticalOffset >= STEP_SIZE) {\n // Compute a delta that guarantees that lines are positioned at `lineHeight` increments\n bigNumbersDelta = Math.floor(startLineNumberVerticalOffset / STEP_SIZE) * STEP_SIZE;\n bigNumbersDelta = Math.floor(bigNumbersDelta / lineHeight) * lineHeight;\n currentLineRelativeOffset -= bigNumbersDelta;\n }\n var linesOffsets = [];\n var verticalCenter = verticalOffset1 + (verticalOffset2 - verticalOffset1) / 2;\n var centeredLineNumber = -1;\n // Figure out how far the lines go\n for (var lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {\n if (centeredLineNumber === -1) {\n var currentLineTop = currentVerticalOffset;\n var currentLineBottom = currentVerticalOffset + lineHeight;\n if ((currentLineTop <= verticalCenter && verticalCenter < currentLineBottom) || currentLineTop > verticalCenter) {\n centeredLineNumber = lineNumber;\n }\n }\n // Count current line height in the vertical offsets\n currentVerticalOffset += lineHeight;\n linesOffsets[lineNumber - startLineNumber] = currentLineRelativeOffset;\n // Next line starts immediately after this one\n currentLineRelativeOffset += lineHeight;\n while (currentWhitespaceAfterLineNumber === lineNumber) {\n // Push down next line with the height of the current whitespace\n currentLineRelativeOffset += currentWhitespaceHeight;\n // Count current whitespace in the vertical offsets\n currentVerticalOffset += currentWhitespaceHeight;\n whitespaceIndex++;\n if (whitespaceIndex >= whitespaceCount) {\n currentWhitespaceAfterLineNumber = endLineNumber + 1;\n }\n else {\n currentWhitespaceAfterLineNumber = this._whitespaces.getAfterLineNumberForWhitespaceIndex(whitespaceIndex) | 0;\n currentWhitespaceHeight = this._whitespaces.getHeightForWhitespaceIndex(whitespaceIndex) | 0;\n }\n }\n if (currentVerticalOffset >= verticalOffset2) {\n // We have covered the entire viewport area, time to stop\n endLineNumber = lineNumber;\n break;\n }\n }\n if (centeredLineNumber === -1) {\n centeredLineNumber = endLineNumber;\n }\n var endLineNumberVerticalOffset = this.getVerticalOffsetForLineNumber(endLineNumber) | 0;\n var completelyVisibleStartLineNumber = startLineNumber;\n var completelyVisibleEndLineNumber = endLineNumber;\n if (completelyVisibleStartLineNumber < completelyVisibleEndLineNumber) {\n if (startLineNumberVerticalOffset < verticalOffset1) {\n completelyVisibleStartLineNumber++;\n }\n }\n if (completelyVisibleStartLineNumber < completelyVisibleEndLineNumber) {\n if (endLineNumberVerticalOffset + lineHeight > verticalOffset2) {\n completelyVisibleEndLineNumber--;\n }\n }\n return {\n bigNumbersDelta: bigNumbersDelta,\n startLineNumber: startLineNumber,\n endLineNumber: endLineNumber,\n relativeVerticalOffset: linesOffsets,\n centeredLineNumber: centeredLineNumber,\n completelyVisibleStartLineNumber: completelyVisibleStartLineNumber,\n completelyVisibleEndLineNumber: completelyVisibleEndLineNumber\n };\n };\n LinesLayout.prototype.getVerticalOffsetForWhitespaceIndex = function (whitespaceIndex) {\n whitespaceIndex = whitespaceIndex | 0;\n var afterLineNumber = this._whitespaces.getAfterLineNumberForWhitespaceIndex(whitespaceIndex);\n var previousLinesHeight;\n if (afterLineNumber >= 1) {\n previousLinesHeight = this._lineHeight * afterLineNumber;\n }\n else {\n previousLinesHeight = 0;\n }\n var previousWhitespacesHeight;\n if (whitespaceIndex > 0) {\n previousWhitespacesHeight = this._whitespaces.getAccumulatedHeight(whitespaceIndex - 1);\n }\n else {\n previousWhitespacesHeight = 0;\n }\n return previousLinesHeight + previousWhitespacesHeight;\n };\n LinesLayout.prototype.getWhitespaceIndexAtOrAfterVerticallOffset = function (verticalOffset) {\n verticalOffset = verticalOffset | 0;\n var midWhitespaceIndex, minWhitespaceIndex = 0, maxWhitespaceIndex = this._whitespaces.getCount() - 1, midWhitespaceVerticalOffset, midWhitespaceHeight;\n if (maxWhitespaceIndex < 0) {\n return -1;\n }\n // Special case: nothing to be found\n var maxWhitespaceVerticalOffset = this.getVerticalOffsetForWhitespaceIndex(maxWhitespaceIndex);\n var maxWhitespaceHeight = this._whitespaces.getHeightForWhitespaceIndex(maxWhitespaceIndex);\n if (verticalOffset >= maxWhitespaceVerticalOffset + maxWhitespaceHeight) {\n return -1;\n }\n while (minWhitespaceIndex < maxWhitespaceIndex) {\n midWhitespaceIndex = Math.floor((minWhitespaceIndex + maxWhitespaceIndex) / 2);\n midWhitespaceVerticalOffset = this.getVerticalOffsetForWhitespaceIndex(midWhitespaceIndex);\n midWhitespaceHeight = this._whitespaces.getHeightForWhitespaceIndex(midWhitespaceIndex);\n if (verticalOffset >= midWhitespaceVerticalOffset + midWhitespaceHeight) {\n // vertical offset is after whitespace\n minWhitespaceIndex = midWhitespaceIndex + 1;\n }\n else if (verticalOffset >= midWhitespaceVerticalOffset) {\n // Hit\n return midWhitespaceIndex;\n }\n else {\n // vertical offset is before whitespace, but midWhitespaceIndex might still be what we're searching for\n maxWhitespaceIndex = midWhitespaceIndex;\n }\n }\n return minWhitespaceIndex;\n };\n /**\n * Get exactly the whitespace that is layouted at `verticalOffset`.\n *\n * @param verticalOffset The vertical offset.\n * @return Precisely the whitespace that is layouted at `verticaloffset` or null.\n */\n LinesLayout.prototype.getWhitespaceAtVerticalOffset = function (verticalOffset) {\n verticalOffset = verticalOffset | 0;\n var candidateIndex = this.getWhitespaceIndexAtOrAfterVerticallOffset(verticalOffset);\n if (candidateIndex < 0) {\n return null;\n }\n if (candidateIndex >= this._whitespaces.getCount()) {\n return null;\n }\n var candidateTop = this.getVerticalOffsetForWhitespaceIndex(candidateIndex);\n if (candidateTop > verticalOffset) {\n return null;\n }\n var candidateHeight = this._whitespaces.getHeightForWhitespaceIndex(candidateIndex);\n var candidateId = this._whitespaces.getIdForWhitespaceIndex(candidateIndex);\n var candidateAfterLineNumber = this._whitespaces.getAfterLineNumberForWhitespaceIndex(candidateIndex);\n return {\n id: candidateId,\n afterLineNumber: candidateAfterLineNumber,\n verticalOffset: candidateTop,\n height: candidateHeight\n };\n };\n /**\n * Get a list of whitespaces that are positioned between `verticalOffset1` and `verticalOffset2`.\n *\n * @param verticalOffset1 The beginning of the viewport.\n * @param verticalOffset2 The end of the viewport.\n * @return An array with all the whitespaces in the viewport. If no whitespace is in viewport, the array is empty.\n */\n LinesLayout.prototype.getWhitespaceViewportData = function (verticalOffset1, verticalOffset2) {\n verticalOffset1 = verticalOffset1 | 0;\n verticalOffset2 = verticalOffset2 | 0;\n var startIndex = this.getWhitespaceIndexAtOrAfterVerticallOffset(verticalOffset1);\n var endIndex = this._whitespaces.getCount() - 1;\n if (startIndex < 0) {\n return [];\n }\n var result = [];\n for (var i = startIndex; i <= endIndex; i++) {\n var top_1 = this.getVerticalOffsetForWhitespaceIndex(i);\n var height = this._whitespaces.getHeightForWhitespaceIndex(i);\n if (top_1 >= verticalOffset2) {\n break;\n }\n result.push({\n id: this._whitespaces.getIdForWhitespaceIndex(i),\n afterLineNumber: this._whitespaces.getAfterLineNumberForWhitespaceIndex(i),\n verticalOffset: top_1,\n height: height\n });\n }\n return result;\n };\n /**\n * Get all whitespaces.\n */\n LinesLayout.prototype.getWhitespaces = function () {\n return this._whitespaces.getWhitespaces(this._lineHeight);\n };\n return LinesLayout;\n}());\nexport { LinesLayout };\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { Disposable } from '../../../base/common/lifecycle.js';\nimport { Scrollable } from '../../../base/common/scrollable.js';\nimport { LinesLayout } from './linesLayout.js';\nimport { Viewport } from '../viewModel/viewModel.js';\nvar SMOOTH_SCROLLING_TIME = 125;\nvar ViewLayout = /** @class */ (function (_super) {\n __extends(ViewLayout, _super);\n function ViewLayout(configuration, lineCount, scheduleAtNextAnimationFrame) {\n var _this = _super.call(this) || this;\n _this._configuration = configuration;\n _this._linesLayout = new LinesLayout(lineCount, _this._configuration.editor.lineHeight);\n _this.scrollable = _this._register(new Scrollable(0, scheduleAtNextAnimationFrame));\n _this._configureSmoothScrollDuration();\n _this.scrollable.setScrollDimensions({\n width: configuration.editor.layoutInfo.contentWidth,\n height: configuration.editor.layoutInfo.contentHeight\n });\n _this.onDidScroll = _this.scrollable.onScroll;\n _this._updateHeight();\n return _this;\n }\n ViewLayout.prototype.dispose = function () {\n _super.prototype.dispose.call(this);\n };\n ViewLayout.prototype.onHeightMaybeChanged = function () {\n this._updateHeight();\n };\n ViewLayout.prototype._configureSmoothScrollDuration = function () {\n this.scrollable.setSmoothScrollDuration(this._configuration.editor.viewInfo.smoothScrolling ? SMOOTH_SCROLLING_TIME : 0);\n };\n // ---- begin view event handlers\n ViewLayout.prototype.onConfigurationChanged = function (e) {\n if (e.lineHeight) {\n this._linesLayout.setLineHeight(this._configuration.editor.lineHeight);\n }\n if (e.layoutInfo) {\n this.scrollable.setScrollDimensions({\n width: this._configuration.editor.layoutInfo.contentWidth,\n height: this._configuration.editor.layoutInfo.contentHeight\n });\n }\n if (e.viewInfo) {\n this._configureSmoothScrollDuration();\n }\n this._updateHeight();\n };\n ViewLayout.prototype.onFlushed = function (lineCount) {\n this._linesLayout.onFlushed(lineCount);\n };\n ViewLayout.prototype.onLinesDeleted = function (fromLineNumber, toLineNumber) {\n this._linesLayout.onLinesDeleted(fromLineNumber, toLineNumber);\n };\n ViewLayout.prototype.onLinesInserted = function (fromLineNumber, toLineNumber) {\n this._linesLayout.onLinesInserted(fromLineNumber, toLineNumber);\n };\n // ---- end view event handlers\n ViewLayout.prototype._getHorizontalScrollbarHeight = function (scrollDimensions) {\n if (this._configuration.editor.viewInfo.scrollbar.horizontal === 2 /* Hidden */) {\n // horizontal scrollbar not visible\n return 0;\n }\n if (scrollDimensions.width >= scrollDimensions.scrollWidth) {\n // horizontal scrollbar not visible\n return 0;\n }\n return this._configuration.editor.viewInfo.scrollbar.horizontalScrollbarSize;\n };\n ViewLayout.prototype._getTotalHeight = function () {\n var scrollDimensions = this.scrollable.getScrollDimensions();\n var result = this._linesLayout.getLinesTotalHeight();\n if (this._configuration.editor.viewInfo.scrollBeyondLastLine) {\n result += scrollDimensions.height - this._configuration.editor.lineHeight;\n }\n else {\n result += this._getHorizontalScrollbarHeight(scrollDimensions);\n }\n return Math.max(scrollDimensions.height, result);\n };\n ViewLayout.prototype._updateHeight = function () {\n this.scrollable.setScrollDimensions({\n scrollHeight: this._getTotalHeight()\n });\n };\n // ---- Layouting logic\n ViewLayout.prototype.getCurrentViewport = function () {\n var scrollDimensions = this.scrollable.getScrollDimensions();\n var currentScrollPosition = this.scrollable.getCurrentScrollPosition();\n return new Viewport(currentScrollPosition.scrollTop, currentScrollPosition.scrollLeft, scrollDimensions.width, scrollDimensions.height);\n };\n ViewLayout.prototype.getFutureViewport = function () {\n var scrollDimensions = this.scrollable.getScrollDimensions();\n var currentScrollPosition = this.scrollable.getFutureScrollPosition();\n return new Viewport(currentScrollPosition.scrollTop, currentScrollPosition.scrollLeft, scrollDimensions.width, scrollDimensions.height);\n };\n ViewLayout.prototype._computeScrollWidth = function (maxLineWidth, viewportWidth) {\n var isViewportWrapping = this._configuration.editor.wrappingInfo.isViewportWrapping;\n if (!isViewportWrapping) {\n var extraHorizontalSpace = this._configuration.editor.viewInfo.scrollBeyondLastColumn * this._configuration.editor.fontInfo.typicalHalfwidthCharacterWidth;\n var whitespaceMinWidth = this._linesLayout.getWhitespaceMinWidth();\n return Math.max(maxLineWidth + extraHorizontalSpace, viewportWidth, whitespaceMinWidth);\n }\n return Math.max(maxLineWidth, viewportWidth);\n };\n ViewLayout.prototype.onMaxLineWidthChanged = function (maxLineWidth) {\n var newScrollWidth = this._computeScrollWidth(maxLineWidth, this.getCurrentViewport().width);\n this.scrollable.setScrollDimensions({\n scrollWidth: newScrollWidth\n });\n // The height might depend on the fact that there is a horizontal scrollbar or not\n this._updateHeight();\n };\n // ---- view state\n ViewLayout.prototype.saveState = function () {\n var currentScrollPosition = this.scrollable.getFutureScrollPosition();\n var scrollTop = currentScrollPosition.scrollTop;\n var firstLineNumberInViewport = this._linesLayout.getLineNumberAtOrAfterVerticalOffset(scrollTop);\n var whitespaceAboveFirstLine = this._linesLayout.getWhitespaceAccumulatedHeightBeforeLineNumber(firstLineNumberInViewport);\n return {\n scrollTop: scrollTop,\n scrollTopWithoutViewZones: scrollTop - whitespaceAboveFirstLine,\n scrollLeft: currentScrollPosition.scrollLeft\n };\n };\n // ---- IVerticalLayoutProvider\n ViewLayout.prototype.addWhitespace = function (afterLineNumber, ordinal, height, minWidth) {\n return this._linesLayout.insertWhitespace(afterLineNumber, ordinal, height, minWidth);\n };\n ViewLayout.prototype.changeWhitespace = function (id, newAfterLineNumber, newHeight) {\n return this._linesLayout.changeWhitespace(id, newAfterLineNumber, newHeight);\n };\n ViewLayout.prototype.removeWhitespace = function (id) {\n return this._linesLayout.removeWhitespace(id);\n };\n ViewLayout.prototype.getVerticalOffsetForLineNumber = function (lineNumber) {\n return this._linesLayout.getVerticalOffsetForLineNumber(lineNumber);\n };\n ViewLayout.prototype.isAfterLines = function (verticalOffset) {\n return this._linesLayout.isAfterLines(verticalOffset);\n };\n ViewLayout.prototype.getLineNumberAtVerticalOffset = function (verticalOffset) {\n return this._linesLayout.getLineNumberAtOrAfterVerticalOffset(verticalOffset);\n };\n ViewLayout.prototype.getWhitespaceAtVerticalOffset = function (verticalOffset) {\n return this._linesLayout.getWhitespaceAtVerticalOffset(verticalOffset);\n };\n ViewLayout.prototype.getLinesViewportData = function () {\n var visibleBox = this.getCurrentViewport();\n return this._linesLayout.getLinesViewportData(visibleBox.top, visibleBox.top + visibleBox.height);\n };\n ViewLayout.prototype.getLinesViewportDataAtScrollTop = function (scrollTop) {\n // do some minimal validations on scrollTop\n var scrollDimensions = this.scrollable.getScrollDimensions();\n if (scrollTop + scrollDimensions.height > scrollDimensions.scrollHeight) {\n scrollTop = scrollDimensions.scrollHeight - scrollDimensions.height;\n }\n if (scrollTop < 0) {\n scrollTop = 0;\n }\n return this._linesLayout.getLinesViewportData(scrollTop, scrollTop + scrollDimensions.height);\n };\n ViewLayout.prototype.getWhitespaceViewportData = function () {\n var visibleBox = this.getCurrentViewport();\n return this._linesLayout.getWhitespaceViewportData(visibleBox.top, visibleBox.top + visibleBox.height);\n };\n ViewLayout.prototype.getWhitespaces = function () {\n return this._linesLayout.getWhitespaces();\n };\n // ---- IScrollingProvider\n ViewLayout.prototype.getScrollWidth = function () {\n var scrollDimensions = this.scrollable.getScrollDimensions();\n return scrollDimensions.scrollWidth;\n };\n ViewLayout.prototype.getScrollHeight = function () {\n var scrollDimensions = this.scrollable.getScrollDimensions();\n return scrollDimensions.scrollHeight;\n };\n ViewLayout.prototype.getCurrentScrollLeft = function () {\n var currentScrollPosition = this.scrollable.getCurrentScrollPosition();\n return currentScrollPosition.scrollLeft;\n };\n ViewLayout.prototype.getCurrentScrollTop = function () {\n var currentScrollPosition = this.scrollable.getCurrentScrollPosition();\n return currentScrollPosition.scrollTop;\n };\n ViewLayout.prototype.validateScrollPosition = function (scrollPosition) {\n return this.scrollable.validateScrollPosition(scrollPosition);\n };\n ViewLayout.prototype.setScrollPositionNow = function (position) {\n this.scrollable.setScrollPositionNow(position);\n };\n ViewLayout.prototype.setScrollPositionSmooth = function (position) {\n this.scrollable.setScrollPositionSmooth(position);\n };\n ViewLayout.prototype.deltaScrollNow = function (deltaScrollLeft, deltaScrollTop) {\n var currentScrollPosition = this.scrollable.getCurrentScrollPosition();\n this.scrollable.setScrollPositionNow({\n scrollLeft: currentScrollPosition.scrollLeft + deltaScrollLeft,\n scrollTop: currentScrollPosition.scrollTop + deltaScrollTop\n });\n };\n return ViewLayout;\n}(Disposable));\nexport { ViewLayout };\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport { Position } from '../core/position.js';\nimport { Range } from '../core/range.js';\nimport { ModelDecorationOptions } from '../model/textModel.js';\nimport * as viewEvents from '../view/viewEvents.js';\nimport { PrefixSumComputerWithCache } from './prefixSumComputer.js';\nimport { ViewLineData } from './viewModel.js';\nvar OutputPosition = /** @class */ (function () {\n function OutputPosition(outputLineIndex, outputOffset) {\n this.outputLineIndex = outputLineIndex;\n this.outputOffset = outputOffset;\n }\n return OutputPosition;\n}());\nexport { OutputPosition };\nvar CoordinatesConverter = /** @class */ (function () {\n function CoordinatesConverter(lines) {\n this._lines = lines;\n }\n // View -> Model conversion and related methods\n CoordinatesConverter.prototype.convertViewPositionToModelPosition = function (viewPosition) {\n return this._lines.convertViewPositionToModelPosition(viewPosition.lineNumber, viewPosition.column);\n };\n CoordinatesConverter.prototype.convertViewRangeToModelRange = function (viewRange) {\n var start = this._lines.convertViewPositionToModelPosition(viewRange.startLineNumber, viewRange.startColumn);\n var end = this._lines.convertViewPositionToModelPosition(viewRange.endLineNumber, viewRange.endColumn);\n return new Range(start.lineNumber, start.column, end.lineNumber, end.column);\n };\n CoordinatesConverter.prototype.validateViewPosition = function (viewPosition, expectedModelPosition) {\n return this._lines.validateViewPosition(viewPosition.lineNumber, viewPosition.column, expectedModelPosition);\n };\n CoordinatesConverter.prototype.validateViewRange = function (viewRange, expectedModelRange) {\n var validViewStart = this._lines.validateViewPosition(viewRange.startLineNumber, viewRange.startColumn, expectedModelRange.getStartPosition());\n var validViewEnd = this._lines.validateViewPosition(viewRange.endLineNumber, viewRange.endColumn, expectedModelRange.getEndPosition());\n return new Range(validViewStart.lineNumber, validViewStart.column, validViewEnd.lineNumber, validViewEnd.column);\n };\n // Model -> View conversion and related methods\n CoordinatesConverter.prototype.convertModelPositionToViewPosition = function (modelPosition) {\n return this._lines.convertModelPositionToViewPosition(modelPosition.lineNumber, modelPosition.column);\n };\n CoordinatesConverter.prototype.convertModelRangeToViewRange = function (modelRange) {\n var start = this._lines.convertModelPositionToViewPosition(modelRange.startLineNumber, modelRange.startColumn);\n var end = this._lines.convertModelPositionToViewPosition(modelRange.endLineNumber, modelRange.endColumn);\n return new Range(start.lineNumber, start.column, end.lineNumber, end.column);\n };\n CoordinatesConverter.prototype.modelPositionIsVisible = function (modelPosition) {\n return this._lines.modelPositionIsVisible(modelPosition.lineNumber, modelPosition.column);\n };\n return CoordinatesConverter;\n}());\nexport { CoordinatesConverter };\nvar SplitLinesCollection = /** @class */ (function () {\n function SplitLinesCollection(model, linePositionMapperFactory, tabSize, wrappingColumn, columnsForFullWidthChar, wrappingIndent) {\n this.model = model;\n this._validModelVersionId = -1;\n this.tabSize = tabSize;\n this.wrappingColumn = wrappingColumn;\n this.columnsForFullWidthChar = columnsForFullWidthChar;\n this.wrappingIndent = wrappingIndent;\n this.linePositionMapperFactory = linePositionMapperFactory;\n this._constructLines(true);\n }\n SplitLinesCollection.prototype.dispose = function () {\n this.hiddenAreasIds = this.model.deltaDecorations(this.hiddenAreasIds, []);\n };\n SplitLinesCollection.prototype.createCoordinatesConverter = function () {\n return new CoordinatesConverter(this);\n };\n SplitLinesCollection.prototype._ensureValidState = function () {\n var modelVersion = this.model.getVersionId();\n if (modelVersion !== this._validModelVersionId) {\n // This is pretty bad, it means we lost track of the model...\n throw new Error(\"ViewModel is out of sync with Model!\");\n }\n if (this.lines.length !== this.model.getLineCount()) {\n // This is pretty bad, it means we lost track of the model...\n this._constructLines(false);\n }\n };\n SplitLinesCollection.prototype._constructLines = function (resetHiddenAreas) {\n var _this = this;\n this.lines = [];\n if (resetHiddenAreas) {\n this.hiddenAreasIds = [];\n }\n var linesContent = this.model.getLinesContent();\n var lineCount = linesContent.length;\n var values = new Uint32Array(lineCount);\n var hiddenAreas = this.hiddenAreasIds.map(function (areaId) { return _this.model.getDecorationRange(areaId); }).sort(Range.compareRangesUsingStarts);\n var hiddenAreaStart = 1, hiddenAreaEnd = 0;\n var hiddenAreaIdx = -1;\n var nextLineNumberToUpdateHiddenArea = (hiddenAreaIdx + 1 < hiddenAreas.length) ? hiddenAreaEnd + 1 : lineCount + 2;\n for (var i = 0; i < lineCount; i++) {\n var lineNumber = i + 1;\n if (lineNumber === nextLineNumberToUpdateHiddenArea) {\n hiddenAreaIdx++;\n hiddenAreaStart = hiddenAreas[hiddenAreaIdx].startLineNumber;\n hiddenAreaEnd = hiddenAreas[hiddenAreaIdx].endLineNumber;\n nextLineNumberToUpdateHiddenArea = (hiddenAreaIdx + 1 < hiddenAreas.length) ? hiddenAreaEnd + 1 : lineCount + 2;\n }\n var isInHiddenArea = (lineNumber >= hiddenAreaStart && lineNumber <= hiddenAreaEnd);\n var line = createSplitLine(this.linePositionMapperFactory, linesContent[i], this.tabSize, this.wrappingColumn, this.columnsForFullWidthChar, this.wrappingIndent, !isInHiddenArea);\n values[i] = line.getViewLineCount();\n this.lines[i] = line;\n }\n this._validModelVersionId = this.model.getVersionId();\n this.prefixSumComputer = new PrefixSumComputerWithCache(values);\n };\n SplitLinesCollection.prototype.getHiddenAreas = function () {\n var _this = this;\n return this.hiddenAreasIds.map(function (decId) {\n return _this.model.getDecorationRange(decId);\n });\n };\n SplitLinesCollection.prototype._reduceRanges = function (_ranges) {\n var _this = this;\n if (_ranges.length === 0) {\n return [];\n }\n var ranges = _ranges.map(function (r) { return _this.model.validateRange(r); }).sort(Range.compareRangesUsingStarts);\n var result = [];\n var currentRangeStart = ranges[0].startLineNumber;\n var currentRangeEnd = ranges[0].endLineNumber;\n for (var i = 1, len = ranges.length; i < len; i++) {\n var range = ranges[i];\n if (range.startLineNumber > currentRangeEnd + 1) {\n result.push(new Range(currentRangeStart, 1, currentRangeEnd, 1));\n currentRangeStart = range.startLineNumber;\n currentRangeEnd = range.endLineNumber;\n }\n else if (range.endLineNumber > currentRangeEnd) {\n currentRangeEnd = range.endLineNumber;\n }\n }\n result.push(new Range(currentRangeStart, 1, currentRangeEnd, 1));\n return result;\n };\n SplitLinesCollection.prototype.setHiddenAreas = function (_ranges) {\n var _this = this;\n var newRanges = this._reduceRanges(_ranges);\n // BEGIN TODO@Martin: Please stop calling this method on each model change!\n var oldRanges = this.hiddenAreasIds.map(function (areaId) { return _this.model.getDecorationRange(areaId); }).sort(Range.compareRangesUsingStarts);\n if (newRanges.length === oldRanges.length) {\n var hasDifference = false;\n for (var i = 0; i < newRanges.length; i++) {\n if (!newRanges[i].equalsRange(oldRanges[i])) {\n hasDifference = true;\n break;\n }\n }\n if (!hasDifference) {\n return false;\n }\n }\n // END TODO@Martin: Please stop calling this method on each model change!\n var newDecorations = [];\n for (var _i = 0, newRanges_1 = newRanges; _i < newRanges_1.length; _i++) {\n var newRange = newRanges_1[_i];\n newDecorations.push({\n range: newRange,\n options: ModelDecorationOptions.EMPTY\n });\n }\n this.hiddenAreasIds = this.model.deltaDecorations(this.hiddenAreasIds, newDecorations);\n var hiddenAreas = newRanges;\n var hiddenAreaStart = 1, hiddenAreaEnd = 0;\n var hiddenAreaIdx = -1;\n var nextLineNumberToUpdateHiddenArea = (hiddenAreaIdx + 1 < hiddenAreas.length) ? hiddenAreaEnd + 1 : this.lines.length + 2;\n var hasVisibleLine = false;\n for (var i = 0; i < this.lines.length; i++) {\n var lineNumber = i + 1;\n if (lineNumber === nextLineNumberToUpdateHiddenArea) {\n hiddenAreaIdx++;\n hiddenAreaStart = hiddenAreas[hiddenAreaIdx].startLineNumber;\n hiddenAreaEnd = hiddenAreas[hiddenAreaIdx].endLineNumber;\n nextLineNumberToUpdateHiddenArea = (hiddenAreaIdx + 1 < hiddenAreas.length) ? hiddenAreaEnd + 1 : this.lines.length + 2;\n }\n var lineChanged = false;\n if (lineNumber >= hiddenAreaStart && lineNumber <= hiddenAreaEnd) {\n // Line should be hidden\n if (this.lines[i].isVisible()) {\n this.lines[i] = this.lines[i].setVisible(false);\n lineChanged = true;\n }\n }\n else {\n hasVisibleLine = true;\n // Line should be visible\n if (!this.lines[i].isVisible()) {\n this.lines[i] = this.lines[i].setVisible(true);\n lineChanged = true;\n }\n }\n if (lineChanged) {\n var newOutputLineCount = this.lines[i].getViewLineCount();\n this.prefixSumComputer.changeValue(i, newOutputLineCount);\n }\n }\n if (!hasVisibleLine) {\n // Cannot have everything be hidden => reveal everything!\n this.setHiddenAreas([]);\n }\n return true;\n };\n SplitLinesCollection.prototype.modelPositionIsVisible = function (modelLineNumber, _modelColumn) {\n if (modelLineNumber < 1 || modelLineNumber > this.lines.length) {\n // invalid arguments\n return false;\n }\n return this.lines[modelLineNumber - 1].isVisible();\n };\n SplitLinesCollection.prototype.setTabSize = function (newTabSize) {\n if (this.tabSize === newTabSize) {\n return false;\n }\n this.tabSize = newTabSize;\n this._constructLines(false);\n return true;\n };\n SplitLinesCollection.prototype.setWrappingSettings = function (wrappingIndent, wrappingColumn, columnsForFullWidthChar) {\n if (this.wrappingIndent === wrappingIndent && this.wrappingColumn === wrappingColumn && this.columnsForFullWidthChar === columnsForFullWidthChar) {\n return false;\n }\n this.wrappingIndent = wrappingIndent;\n this.wrappingColumn = wrappingColumn;\n this.columnsForFullWidthChar = columnsForFullWidthChar;\n this._constructLines(false);\n return true;\n };\n SplitLinesCollection.prototype.onModelFlushed = function () {\n this._constructLines(true);\n };\n SplitLinesCollection.prototype.onModelLinesDeleted = function (versionId, fromLineNumber, toLineNumber) {\n if (versionId <= this._validModelVersionId) {\n // Here we check for versionId in case the lines were reconstructed in the meantime.\n // We don't want to apply stale change events on top of a newer read model state.\n return null;\n }\n var outputFromLineNumber = (fromLineNumber === 1 ? 1 : this.prefixSumComputer.getAccumulatedValue(fromLineNumber - 2) + 1);\n var outputToLineNumber = this.prefixSumComputer.getAccumulatedValue(toLineNumber - 1);\n this.lines.splice(fromLineNumber - 1, toLineNumber - fromLineNumber + 1);\n this.prefixSumComputer.removeValues(fromLineNumber - 1, toLineNumber - fromLineNumber + 1);\n return new viewEvents.ViewLinesDeletedEvent(outputFromLineNumber, outputToLineNumber);\n };\n SplitLinesCollection.prototype.onModelLinesInserted = function (versionId, fromLineNumber, _toLineNumber, text) {\n if (versionId <= this._validModelVersionId) {\n // Here we check for versionId in case the lines were reconstructed in the meantime.\n // We don't want to apply stale change events on top of a newer read model state.\n return null;\n }\n var hiddenAreas = this.getHiddenAreas();\n var isInHiddenArea = false;\n var testPosition = new Position(fromLineNumber, 1);\n for (var _i = 0, hiddenAreas_1 = hiddenAreas; _i < hiddenAreas_1.length; _i++) {\n var hiddenArea = hiddenAreas_1[_i];\n if (hiddenArea.containsPosition(testPosition)) {\n isInHiddenArea = true;\n break;\n }\n }\n var outputFromLineNumber = (fromLineNumber === 1 ? 1 : this.prefixSumComputer.getAccumulatedValue(fromLineNumber - 2) + 1);\n var totalOutputLineCount = 0;\n var insertLines = [];\n var insertPrefixSumValues = new Uint32Array(text.length);\n for (var i = 0, len = text.length; i < len; i++) {\n var line = createSplitLine(this.linePositionMapperFactory, text[i], this.tabSize, this.wrappingColumn, this.columnsForFullWidthChar, this.wrappingIndent, !isInHiddenArea);\n insertLines.push(line);\n var outputLineCount = line.getViewLineCount();\n totalOutputLineCount += outputLineCount;\n insertPrefixSumValues[i] = outputLineCount;\n }\n // TODO@Alex: use arrays.arrayInsert\n this.lines = this.lines.slice(0, fromLineNumber - 1).concat(insertLines).concat(this.lines.slice(fromLineNumber - 1));\n this.prefixSumComputer.insertValues(fromLineNumber - 1, insertPrefixSumValues);\n return new viewEvents.ViewLinesInsertedEvent(outputFromLineNumber, outputFromLineNumber + totalOutputLineCount - 1);\n };\n SplitLinesCollection.prototype.onModelLineChanged = function (versionId, lineNumber, newText) {\n if (versionId <= this._validModelVersionId) {\n // Here we check for versionId in case the lines were reconstructed in the meantime.\n // We don't want to apply stale change events on top of a newer read model state.\n return [false, null, null, null];\n }\n var lineIndex = lineNumber - 1;\n var oldOutputLineCount = this.lines[lineIndex].getViewLineCount();\n var isVisible = this.lines[lineIndex].isVisible();\n var line = createSplitLine(this.linePositionMapperFactory, newText, this.tabSize, this.wrappingColumn, this.columnsForFullWidthChar, this.wrappingIndent, isVisible);\n this.lines[lineIndex] = line;\n var newOutputLineCount = this.lines[lineIndex].getViewLineCount();\n var lineMappingChanged = false;\n var changeFrom = 0;\n var changeTo = -1;\n var insertFrom = 0;\n var insertTo = -1;\n var deleteFrom = 0;\n var deleteTo = -1;\n if (oldOutputLineCount > newOutputLineCount) {\n changeFrom = (lineNumber === 1 ? 1 : this.prefixSumComputer.getAccumulatedValue(lineNumber - 2) + 1);\n changeTo = changeFrom + newOutputLineCount - 1;\n deleteFrom = changeTo + 1;\n deleteTo = deleteFrom + (oldOutputLineCount - newOutputLineCount) - 1;\n lineMappingChanged = true;\n }\n else if (oldOutputLineCount < newOutputLineCount) {\n changeFrom = (lineNumber === 1 ? 1 : this.prefixSumComputer.getAccumulatedValue(lineNumber - 2) + 1);\n changeTo = changeFrom + oldOutputLineCount - 1;\n insertFrom = changeTo + 1;\n insertTo = insertFrom + (newOutputLineCount - oldOutputLineCount) - 1;\n lineMappingChanged = true;\n }\n else {\n changeFrom = (lineNumber === 1 ? 1 : this.prefixSumComputer.getAccumulatedValue(lineNumber - 2) + 1);\n changeTo = changeFrom + newOutputLineCount - 1;\n }\n this.prefixSumComputer.changeValue(lineIndex, newOutputLineCount);\n var viewLinesChangedEvent = (changeFrom <= changeTo ? new viewEvents.ViewLinesChangedEvent(changeFrom, changeTo) : null);\n var viewLinesInsertedEvent = (insertFrom <= insertTo ? new viewEvents.ViewLinesInsertedEvent(insertFrom, insertTo) : null);\n var viewLinesDeletedEvent = (deleteFrom <= deleteTo ? new viewEvents.ViewLinesDeletedEvent(deleteFrom, deleteTo) : null);\n return [lineMappingChanged, viewLinesChangedEvent, viewLinesInsertedEvent, viewLinesDeletedEvent];\n };\n SplitLinesCollection.prototype.acceptVersionId = function (versionId) {\n this._validModelVersionId = versionId;\n if (this.lines.length === 1 && !this.lines[0].isVisible()) {\n // At least one line must be visible => reset hidden areas\n this.setHiddenAreas([]);\n }\n };\n SplitLinesCollection.prototype.getViewLineCount = function () {\n this._ensureValidState();\n return this.prefixSumComputer.getTotalValue();\n };\n SplitLinesCollection.prototype._toValidViewLineNumber = function (viewLineNumber) {\n if (viewLineNumber < 1) {\n return 1;\n }\n var viewLineCount = this.getViewLineCount();\n if (viewLineNumber > viewLineCount) {\n return viewLineCount;\n }\n return viewLineNumber;\n };\n /**\n * Gives a hint that a lot of requests are about to come in for these line numbers.\n */\n SplitLinesCollection.prototype.warmUpLookupCache = function (viewStartLineNumber, viewEndLineNumber) {\n this.prefixSumComputer.warmUpCache(viewStartLineNumber - 1, viewEndLineNumber - 1);\n };\n SplitLinesCollection.prototype.getActiveIndentGuide = function (viewLineNumber, minLineNumber, maxLineNumber) {\n this._ensureValidState();\n viewLineNumber = this._toValidViewLineNumber(viewLineNumber);\n minLineNumber = this._toValidViewLineNumber(minLineNumber);\n maxLineNumber = this._toValidViewLineNumber(maxLineNumber);\n var modelPosition = this.convertViewPositionToModelPosition(viewLineNumber, this.getViewLineMinColumn(viewLineNumber));\n var modelMinPosition = this.convertViewPositionToModelPosition(minLineNumber, this.getViewLineMinColumn(minLineNumber));\n var modelMaxPosition = this.convertViewPositionToModelPosition(maxLineNumber, this.getViewLineMinColumn(maxLineNumber));\n var result = this.model.getActiveIndentGuide(modelPosition.lineNumber, modelMinPosition.lineNumber, modelMaxPosition.lineNumber);\n var viewStartPosition = this.convertModelPositionToViewPosition(result.startLineNumber, 1);\n var viewEndPosition = this.convertModelPositionToViewPosition(result.endLineNumber, this.model.getLineMaxColumn(result.endLineNumber));\n return {\n startLineNumber: viewStartPosition.lineNumber,\n endLineNumber: viewEndPosition.lineNumber,\n indent: result.indent\n };\n };\n SplitLinesCollection.prototype.getViewLinesIndentGuides = function (viewStartLineNumber, viewEndLineNumber) {\n this._ensureValidState();\n viewStartLineNumber = this._toValidViewLineNumber(viewStartLineNumber);\n viewEndLineNumber = this._toValidViewLineNumber(viewEndLineNumber);\n var modelStart = this.convertViewPositionToModelPosition(viewStartLineNumber, this.getViewLineMinColumn(viewStartLineNumber));\n var modelEnd = this.convertViewPositionToModelPosition(viewEndLineNumber, this.getViewLineMaxColumn(viewEndLineNumber));\n var result = [];\n var resultRepeatCount = [];\n var resultRepeatOption = [];\n var modelStartLineIndex = modelStart.lineNumber - 1;\n var modelEndLineIndex = modelEnd.lineNumber - 1;\n var reqStart = null;\n for (var modelLineIndex = modelStartLineIndex; modelLineIndex <= modelEndLineIndex; modelLineIndex++) {\n var line = this.lines[modelLineIndex];\n if (line.isVisible()) {\n var viewLineStartIndex = line.getViewLineNumberOfModelPosition(0, modelLineIndex === modelStartLineIndex ? modelStart.column : 1);\n var viewLineEndIndex = line.getViewLineNumberOfModelPosition(0, this.model.getLineMaxColumn(modelLineIndex + 1));\n var count = viewLineEndIndex - viewLineStartIndex + 1;\n var option = 0 /* BlockNone */;\n if (count > 1 && line.getViewLineMinColumn(this.model, modelLineIndex + 1, viewLineEndIndex) === 1) {\n // wrapped lines should block indent guides\n option = (viewLineStartIndex === 0 ? 1 /* BlockSubsequent */ : 2 /* BlockAll */);\n }\n resultRepeatCount.push(count);\n resultRepeatOption.push(option);\n // merge into previous request\n if (reqStart === null) {\n reqStart = new Position(modelLineIndex + 1, 0);\n }\n }\n else {\n // hit invisible line => flush request\n if (reqStart !== null) {\n result = result.concat(this.model.getLinesIndentGuides(reqStart.lineNumber, modelLineIndex));\n reqStart = null;\n }\n }\n }\n if (reqStart !== null) {\n result = result.concat(this.model.getLinesIndentGuides(reqStart.lineNumber, modelEnd.lineNumber));\n reqStart = null;\n }\n var viewLineCount = viewEndLineNumber - viewStartLineNumber + 1;\n var viewIndents = new Array(viewLineCount);\n var currIndex = 0;\n for (var i = 0, len = result.length; i < len; i++) {\n var value = result[i];\n var count = Math.min(viewLineCount - currIndex, resultRepeatCount[i]);\n var option = resultRepeatOption[i];\n var blockAtIndex = void 0;\n if (option === 2 /* BlockAll */) {\n blockAtIndex = 0;\n }\n else if (option === 1 /* BlockSubsequent */) {\n blockAtIndex = 1;\n }\n else {\n blockAtIndex = count;\n }\n for (var j = 0; j < count; j++) {\n if (j === blockAtIndex) {\n value = 0;\n }\n viewIndents[currIndex++] = value;\n }\n }\n return viewIndents;\n };\n SplitLinesCollection.prototype.getViewLineContent = function (viewLineNumber) {\n this._ensureValidState();\n viewLineNumber = this._toValidViewLineNumber(viewLineNumber);\n var r = this.prefixSumComputer.getIndexOf(viewLineNumber - 1);\n var lineIndex = r.index;\n var remainder = r.remainder;\n return this.lines[lineIndex].getViewLineContent(this.model, lineIndex + 1, remainder);\n };\n SplitLinesCollection.prototype.getViewLineLength = function (viewLineNumber) {\n this._ensureValidState();\n viewLineNumber = this._toValidViewLineNumber(viewLineNumber);\n var r = this.prefixSumComputer.getIndexOf(viewLineNumber - 1);\n var lineIndex = r.index;\n var remainder = r.remainder;\n return this.lines[lineIndex].getViewLineLength(this.model, lineIndex + 1, remainder);\n };\n SplitLinesCollection.prototype.getViewLineMinColumn = function (viewLineNumber) {\n this._ensureValidState();\n viewLineNumber = this._toValidViewLineNumber(viewLineNumber);\n var r = this.prefixSumComputer.getIndexOf(viewLineNumber - 1);\n var lineIndex = r.index;\n var remainder = r.remainder;\n return this.lines[lineIndex].getViewLineMinColumn(this.model, lineIndex + 1, remainder);\n };\n SplitLinesCollection.prototype.getViewLineMaxColumn = function (viewLineNumber) {\n this._ensureValidState();\n viewLineNumber = this._toValidViewLineNumber(viewLineNumber);\n var r = this.prefixSumComputer.getIndexOf(viewLineNumber - 1);\n var lineIndex = r.index;\n var remainder = r.remainder;\n return this.lines[lineIndex].getViewLineMaxColumn(this.model, lineIndex + 1, remainder);\n };\n SplitLinesCollection.prototype.getViewLineData = function (viewLineNumber) {\n this._ensureValidState();\n viewLineNumber = this._toValidViewLineNumber(viewLineNumber);\n var r = this.prefixSumComputer.getIndexOf(viewLineNumber - 1);\n var lineIndex = r.index;\n var remainder = r.remainder;\n return this.lines[lineIndex].getViewLineData(this.model, lineIndex + 1, remainder);\n };\n SplitLinesCollection.prototype.getViewLinesData = function (viewStartLineNumber, viewEndLineNumber, needed) {\n this._ensureValidState();\n viewStartLineNumber = this._toValidViewLineNumber(viewStartLineNumber);\n viewEndLineNumber = this._toValidViewLineNumber(viewEndLineNumber);\n var start = this.prefixSumComputer.getIndexOf(viewStartLineNumber - 1);\n var viewLineNumber = viewStartLineNumber;\n var startModelLineIndex = start.index;\n var startRemainder = start.remainder;\n var result = [];\n for (var modelLineIndex = startModelLineIndex, len = this.model.getLineCount(); modelLineIndex < len; modelLineIndex++) {\n var line = this.lines[modelLineIndex];\n if (!line.isVisible()) {\n continue;\n }\n var fromViewLineIndex = (modelLineIndex === startModelLineIndex ? startRemainder : 0);\n var remainingViewLineCount = line.getViewLineCount() - fromViewLineIndex;\n var lastLine = false;\n if (viewLineNumber + remainingViewLineCount > viewEndLineNumber) {\n lastLine = true;\n remainingViewLineCount = viewEndLineNumber - viewLineNumber + 1;\n }\n var toViewLineIndex = fromViewLineIndex + remainingViewLineCount;\n line.getViewLinesData(this.model, modelLineIndex + 1, fromViewLineIndex, toViewLineIndex, viewLineNumber - viewStartLineNumber, needed, result);\n viewLineNumber += remainingViewLineCount;\n if (lastLine) {\n break;\n }\n }\n return result;\n };\n SplitLinesCollection.prototype.validateViewPosition = function (viewLineNumber, viewColumn, expectedModelPosition) {\n this._ensureValidState();\n viewLineNumber = this._toValidViewLineNumber(viewLineNumber);\n var r = this.prefixSumComputer.getIndexOf(viewLineNumber - 1);\n var lineIndex = r.index;\n var remainder = r.remainder;\n var line = this.lines[lineIndex];\n var minColumn = line.getViewLineMinColumn(this.model, lineIndex + 1, remainder);\n var maxColumn = line.getViewLineMaxColumn(this.model, lineIndex + 1, remainder);\n if (viewColumn < minColumn) {\n viewColumn = minColumn;\n }\n if (viewColumn > maxColumn) {\n viewColumn = maxColumn;\n }\n var computedModelColumn = line.getModelColumnOfViewPosition(remainder, viewColumn);\n var computedModelPosition = this.model.validatePosition(new Position(lineIndex + 1, computedModelColumn));\n if (computedModelPosition.equals(expectedModelPosition)) {\n return new Position(viewLineNumber, viewColumn);\n }\n return this.convertModelPositionToViewPosition(expectedModelPosition.lineNumber, expectedModelPosition.column);\n };\n SplitLinesCollection.prototype.convertViewPositionToModelPosition = function (viewLineNumber, viewColumn) {\n this._ensureValidState();\n viewLineNumber = this._toValidViewLineNumber(viewLineNumber);\n var r = this.prefixSumComputer.getIndexOf(viewLineNumber - 1);\n var lineIndex = r.index;\n var remainder = r.remainder;\n var inputColumn = this.lines[lineIndex].getModelColumnOfViewPosition(remainder, viewColumn);\n // console.log('out -> in ' + viewLineNumber + ',' + viewColumn + ' ===> ' + (lineIndex+1) + ',' + inputColumn);\n return this.model.validatePosition(new Position(lineIndex + 1, inputColumn));\n };\n SplitLinesCollection.prototype.convertModelPositionToViewPosition = function (_modelLineNumber, _modelColumn) {\n this._ensureValidState();\n var validPosition = this.model.validatePosition(new Position(_modelLineNumber, _modelColumn));\n var inputLineNumber = validPosition.lineNumber;\n var inputColumn = validPosition.column;\n var lineIndex = inputLineNumber - 1, lineIndexChanged = false;\n while (lineIndex > 0 && !this.lines[lineIndex].isVisible()) {\n lineIndex--;\n lineIndexChanged = true;\n }\n if (lineIndex === 0 && !this.lines[lineIndex].isVisible()) {\n // Could not reach a real line\n // console.log('in -> out ' + inputLineNumber + ',' + inputColumn + ' ===> ' + 1 + ',' + 1);\n return new Position(1, 1);\n }\n var deltaLineNumber = 1 + (lineIndex === 0 ? 0 : this.prefixSumComputer.getAccumulatedValue(lineIndex - 1));\n var r;\n if (lineIndexChanged) {\n r = this.lines[lineIndex].getViewPositionOfModelPosition(deltaLineNumber, this.model.getLineMaxColumn(lineIndex + 1));\n }\n else {\n r = this.lines[inputLineNumber - 1].getViewPositionOfModelPosition(deltaLineNumber, inputColumn);\n }\n // console.log('in -> out ' + inputLineNumber + ',' + inputColumn + ' ===> ' + r.lineNumber + ',' + r);\n return r;\n };\n SplitLinesCollection.prototype._getViewLineNumberForModelPosition = function (inputLineNumber, inputColumn) {\n var lineIndex = inputLineNumber - 1;\n if (this.lines[lineIndex].isVisible()) {\n // this model line is visible\n var deltaLineNumber_1 = 1 + (lineIndex === 0 ? 0 : this.prefixSumComputer.getAccumulatedValue(lineIndex - 1));\n return this.lines[lineIndex].getViewLineNumberOfModelPosition(deltaLineNumber_1, inputColumn);\n }\n // this model line is not visible\n while (lineIndex > 0 && !this.lines[lineIndex].isVisible()) {\n lineIndex--;\n }\n if (lineIndex === 0 && !this.lines[lineIndex].isVisible()) {\n // Could not reach a real line\n return 1;\n }\n var deltaLineNumber = 1 + (lineIndex === 0 ? 0 : this.prefixSumComputer.getAccumulatedValue(lineIndex - 1));\n return this.lines[lineIndex].getViewLineNumberOfModelPosition(deltaLineNumber, this.model.getLineMaxColumn(lineIndex + 1));\n };\n SplitLinesCollection.prototype.getAllOverviewRulerDecorations = function (ownerId, filterOutValidation, theme) {\n var decorations = this.model.getOverviewRulerDecorations(ownerId, filterOutValidation);\n var result = new OverviewRulerDecorations();\n for (var _i = 0, decorations_1 = decorations; _i < decorations_1.length; _i++) {\n var decoration = decorations_1[_i];\n var opts = decoration.options.overviewRuler;\n var lane = opts ? opts.position : 0;\n if (lane === 0) {\n continue;\n }\n var color = opts.getColor(theme);\n var viewStartLineNumber = this._getViewLineNumberForModelPosition(decoration.range.startLineNumber, decoration.range.startColumn);\n var viewEndLineNumber = this._getViewLineNumberForModelPosition(decoration.range.endLineNumber, decoration.range.endColumn);\n result.accept(color, viewStartLineNumber, viewEndLineNumber, lane);\n }\n return result.result;\n };\n SplitLinesCollection.prototype.getDecorationsInRange = function (range, ownerId, filterOutValidation) {\n var modelStart = this.convertViewPositionToModelPosition(range.startLineNumber, range.startColumn);\n var modelEnd = this.convertViewPositionToModelPosition(range.endLineNumber, range.endColumn);\n if (modelEnd.lineNumber - modelStart.lineNumber <= range.endLineNumber - range.startLineNumber) {\n // most likely there are no hidden lines => fast path\n // fetch decorations from column 1 to cover the case of wrapped lines that have whole line decorations at column 1\n return this.model.getDecorationsInRange(new Range(modelStart.lineNumber, 1, modelEnd.lineNumber, modelEnd.column), ownerId, filterOutValidation);\n }\n var result = [];\n var modelStartLineIndex = modelStart.lineNumber - 1;\n var modelEndLineIndex = modelEnd.lineNumber - 1;\n var reqStart = null;\n for (var modelLineIndex = modelStartLineIndex; modelLineIndex <= modelEndLineIndex; modelLineIndex++) {\n var line = this.lines[modelLineIndex];\n if (line.isVisible()) {\n // merge into previous request\n if (reqStart === null) {\n reqStart = new Position(modelLineIndex + 1, modelLineIndex === modelStartLineIndex ? modelStart.column : 1);\n }\n }\n else {\n // hit invisible line => flush request\n if (reqStart !== null) {\n var maxLineColumn = this.model.getLineMaxColumn(modelLineIndex);\n result = result.concat(this.model.getDecorationsInRange(new Range(reqStart.lineNumber, reqStart.column, modelLineIndex, maxLineColumn), ownerId, filterOutValidation));\n reqStart = null;\n }\n }\n }\n if (reqStart !== null) {\n result = result.concat(this.model.getDecorationsInRange(new Range(reqStart.lineNumber, reqStart.column, modelEnd.lineNumber, modelEnd.column), ownerId, filterOutValidation));\n reqStart = null;\n }\n result.sort(function (a, b) {\n var res = Range.compareRangesUsingStarts(a.range, b.range);\n if (res === 0) {\n if (a.id < b.id) {\n return -1;\n }\n if (a.id > b.id) {\n return 1;\n }\n return 0;\n }\n return res;\n });\n // Eliminate duplicate decorations that might have intersected our visible ranges multiple times\n var finalResult = [], finalResultLen = 0;\n var prevDecId = null;\n for (var _i = 0, result_1 = result; _i < result_1.length; _i++) {\n var dec = result_1[_i];\n var decId = dec.id;\n if (prevDecId === decId) {\n // skip\n continue;\n }\n prevDecId = decId;\n finalResult[finalResultLen++] = dec;\n }\n return finalResult;\n };\n return SplitLinesCollection;\n}());\nexport { SplitLinesCollection };\nvar VisibleIdentitySplitLine = /** @class */ (function () {\n function VisibleIdentitySplitLine() {\n }\n VisibleIdentitySplitLine.prototype.isVisible = function () {\n return true;\n };\n VisibleIdentitySplitLine.prototype.setVisible = function (isVisible) {\n if (isVisible) {\n return this;\n }\n return InvisibleIdentitySplitLine.INSTANCE;\n };\n VisibleIdentitySplitLine.prototype.getViewLineCount = function () {\n return 1;\n };\n VisibleIdentitySplitLine.prototype.getViewLineContent = function (model, modelLineNumber, _outputLineIndex) {\n return model.getLineContent(modelLineNumber);\n };\n VisibleIdentitySplitLine.prototype.getViewLineLength = function (model, modelLineNumber, _outputLineIndex) {\n return model.getLineLength(modelLineNumber);\n };\n VisibleIdentitySplitLine.prototype.getViewLineMinColumn = function (model, modelLineNumber, _outputLineIndex) {\n return model.getLineMinColumn(modelLineNumber);\n };\n VisibleIdentitySplitLine.prototype.getViewLineMaxColumn = function (model, modelLineNumber, _outputLineIndex) {\n return model.getLineMaxColumn(modelLineNumber);\n };\n VisibleIdentitySplitLine.prototype.getViewLineData = function (model, modelLineNumber, _outputLineIndex) {\n var lineTokens = model.getLineTokens(modelLineNumber);\n var lineContent = lineTokens.getLineContent();\n return new ViewLineData(lineContent, false, 1, lineContent.length + 1, lineTokens.inflate());\n };\n VisibleIdentitySplitLine.prototype.getViewLinesData = function (model, modelLineNumber, _fromOuputLineIndex, _toOutputLineIndex, globalStartIndex, needed, result) {\n if (!needed[globalStartIndex]) {\n result[globalStartIndex] = null;\n return;\n }\n result[globalStartIndex] = this.getViewLineData(model, modelLineNumber, 0);\n };\n VisibleIdentitySplitLine.prototype.getModelColumnOfViewPosition = function (_outputLineIndex, outputColumn) {\n return outputColumn;\n };\n VisibleIdentitySplitLine.prototype.getViewPositionOfModelPosition = function (deltaLineNumber, inputColumn) {\n return new Position(deltaLineNumber, inputColumn);\n };\n VisibleIdentitySplitLine.prototype.getViewLineNumberOfModelPosition = function (deltaLineNumber, _inputColumn) {\n return deltaLineNumber;\n };\n VisibleIdentitySplitLine.INSTANCE = new VisibleIdentitySplitLine();\n return VisibleIdentitySplitLine;\n}());\nvar InvisibleIdentitySplitLine = /** @class */ (function () {\n function InvisibleIdentitySplitLine() {\n }\n InvisibleIdentitySplitLine.prototype.isVisible = function () {\n return false;\n };\n InvisibleIdentitySplitLine.prototype.setVisible = function (isVisible) {\n if (!isVisible) {\n return this;\n }\n return VisibleIdentitySplitLine.INSTANCE;\n };\n InvisibleIdentitySplitLine.prototype.getViewLineCount = function () {\n return 0;\n };\n InvisibleIdentitySplitLine.prototype.getViewLineContent = function (_model, _modelLineNumber, _outputLineIndex) {\n throw new Error('Not supported');\n };\n InvisibleIdentitySplitLine.prototype.getViewLineLength = function (_model, _modelLineNumber, _outputLineIndex) {\n throw new Error('Not supported');\n };\n InvisibleIdentitySplitLine.prototype.getViewLineMinColumn = function (_model, _modelLineNumber, _outputLineIndex) {\n throw new Error('Not supported');\n };\n InvisibleIdentitySplitLine.prototype.getViewLineMaxColumn = function (_model, _modelLineNumber, _outputLineIndex) {\n throw new Error('Not supported');\n };\n InvisibleIdentitySplitLine.prototype.getViewLineData = function (_model, _modelLineNumber, _outputLineIndex) {\n throw new Error('Not supported');\n };\n InvisibleIdentitySplitLine.prototype.getViewLinesData = function (_model, _modelLineNumber, _fromOuputLineIndex, _toOutputLineIndex, _globalStartIndex, _needed, _result) {\n throw new Error('Not supported');\n };\n InvisibleIdentitySplitLine.prototype.getModelColumnOfViewPosition = function (_outputLineIndex, _outputColumn) {\n throw new Error('Not supported');\n };\n InvisibleIdentitySplitLine.prototype.getViewPositionOfModelPosition = function (_deltaLineNumber, _inputColumn) {\n throw new Error('Not supported');\n };\n InvisibleIdentitySplitLine.prototype.getViewLineNumberOfModelPosition = function (_deltaLineNumber, _inputColumn) {\n throw new Error('Not supported');\n };\n InvisibleIdentitySplitLine.INSTANCE = new InvisibleIdentitySplitLine();\n return InvisibleIdentitySplitLine;\n}());\nvar SplitLine = /** @class */ (function () {\n function SplitLine(positionMapper, isVisible) {\n this.positionMapper = positionMapper;\n this.wrappedIndent = this.positionMapper.getWrappedLinesIndent();\n this.wrappedIndentLength = this.wrappedIndent.length;\n this.outputLineCount = this.positionMapper.getOutputLineCount();\n this._isVisible = isVisible;\n }\n SplitLine.prototype.isVisible = function () {\n return this._isVisible;\n };\n SplitLine.prototype.setVisible = function (isVisible) {\n this._isVisible = isVisible;\n return this;\n };\n SplitLine.prototype.getViewLineCount = function () {\n if (!this._isVisible) {\n return 0;\n }\n return this.outputLineCount;\n };\n SplitLine.prototype.getInputStartOffsetOfOutputLineIndex = function (outputLineIndex) {\n return this.positionMapper.getInputOffsetOfOutputPosition(outputLineIndex, 0);\n };\n SplitLine.prototype.getInputEndOffsetOfOutputLineIndex = function (model, modelLineNumber, outputLineIndex) {\n if (outputLineIndex + 1 === this.outputLineCount) {\n return model.getLineMaxColumn(modelLineNumber) - 1;\n }\n return this.positionMapper.getInputOffsetOfOutputPosition(outputLineIndex + 1, 0);\n };\n SplitLine.prototype.getViewLineContent = function (model, modelLineNumber, outputLineIndex) {\n if (!this._isVisible) {\n throw new Error('Not supported');\n }\n var startOffset = this.getInputStartOffsetOfOutputLineIndex(outputLineIndex);\n var endOffset = this.getInputEndOffsetOfOutputLineIndex(model, modelLineNumber, outputLineIndex);\n var r = model.getValueInRange({\n startLineNumber: modelLineNumber,\n startColumn: startOffset + 1,\n endLineNumber: modelLineNumber,\n endColumn: endOffset + 1\n });\n if (outputLineIndex > 0) {\n r = this.wrappedIndent + r;\n }\n return r;\n };\n SplitLine.prototype.getViewLineLength = function (model, modelLineNumber, outputLineIndex) {\n if (!this._isVisible) {\n throw new Error('Not supported');\n }\n var startOffset = this.getInputStartOffsetOfOutputLineIndex(outputLineIndex);\n var endOffset = this.getInputEndOffsetOfOutputLineIndex(model, modelLineNumber, outputLineIndex);\n var r = endOffset - startOffset;\n if (outputLineIndex > 0) {\n r = this.wrappedIndent.length + r;\n }\n return r;\n };\n SplitLine.prototype.getViewLineMinColumn = function (_model, _modelLineNumber, outputLineIndex) {\n if (!this._isVisible) {\n throw new Error('Not supported');\n }\n if (outputLineIndex > 0) {\n return this.wrappedIndentLength + 1;\n }\n return 1;\n };\n SplitLine.prototype.getViewLineMaxColumn = function (model, modelLineNumber, outputLineIndex) {\n if (!this._isVisible) {\n throw new Error('Not supported');\n }\n return this.getViewLineContent(model, modelLineNumber, outputLineIndex).length + 1;\n };\n SplitLine.prototype.getViewLineData = function (model, modelLineNumber, outputLineIndex) {\n if (!this._isVisible) {\n throw new Error('Not supported');\n }\n var startOffset = this.getInputStartOffsetOfOutputLineIndex(outputLineIndex);\n var endOffset = this.getInputEndOffsetOfOutputLineIndex(model, modelLineNumber, outputLineIndex);\n var lineContent = model.getValueInRange({\n startLineNumber: modelLineNumber,\n startColumn: startOffset + 1,\n endLineNumber: modelLineNumber,\n endColumn: endOffset + 1\n });\n if (outputLineIndex > 0) {\n lineContent = this.wrappedIndent + lineContent;\n }\n var minColumn = (outputLineIndex > 0 ? this.wrappedIndentLength + 1 : 1);\n var maxColumn = lineContent.length + 1;\n var continuesWithWrappedLine = (outputLineIndex + 1 < this.getViewLineCount());\n var deltaStartIndex = 0;\n if (outputLineIndex > 0) {\n deltaStartIndex = this.wrappedIndentLength;\n }\n var lineTokens = model.getLineTokens(modelLineNumber);\n return new ViewLineData(lineContent, continuesWithWrappedLine, minColumn, maxColumn, lineTokens.sliceAndInflate(startOffset, endOffset, deltaStartIndex));\n };\n SplitLine.prototype.getViewLinesData = function (model, modelLineNumber, fromOuputLineIndex, toOutputLineIndex, globalStartIndex, needed, result) {\n if (!this._isVisible) {\n throw new Error('Not supported');\n }\n for (var outputLineIndex = fromOuputLineIndex; outputLineIndex < toOutputLineIndex; outputLineIndex++) {\n var globalIndex = globalStartIndex + outputLineIndex - fromOuputLineIndex;\n if (!needed[globalIndex]) {\n result[globalIndex] = null;\n continue;\n }\n result[globalIndex] = this.getViewLineData(model, modelLineNumber, outputLineIndex);\n }\n };\n SplitLine.prototype.getModelColumnOfViewPosition = function (outputLineIndex, outputColumn) {\n if (!this._isVisible) {\n throw new Error('Not supported');\n }\n var adjustedColumn = outputColumn - 1;\n if (outputLineIndex > 0) {\n if (adjustedColumn < this.wrappedIndentLength) {\n adjustedColumn = 0;\n }\n else {\n adjustedColumn -= this.wrappedIndentLength;\n }\n }\n return this.positionMapper.getInputOffsetOfOutputPosition(outputLineIndex, adjustedColumn) + 1;\n };\n SplitLine.prototype.getViewPositionOfModelPosition = function (deltaLineNumber, inputColumn) {\n if (!this._isVisible) {\n throw new Error('Not supported');\n }\n var r = this.positionMapper.getOutputPositionOfInputOffset(inputColumn - 1);\n var outputLineIndex = r.outputLineIndex;\n var outputColumn = r.outputOffset + 1;\n if (outputLineIndex > 0) {\n outputColumn += this.wrappedIndentLength;\n }\n //\t\tconsole.log('in -> out ' + deltaLineNumber + ',' + inputColumn + ' ===> ' + (deltaLineNumber+outputLineIndex) + ',' + outputColumn);\n return new Position(deltaLineNumber + outputLineIndex, outputColumn);\n };\n SplitLine.prototype.getViewLineNumberOfModelPosition = function (deltaLineNumber, inputColumn) {\n if (!this._isVisible) {\n throw new Error('Not supported');\n }\n var r = this.positionMapper.getOutputPositionOfInputOffset(inputColumn - 1);\n return (deltaLineNumber + r.outputLineIndex);\n };\n return SplitLine;\n}());\nexport { SplitLine };\nfunction createSplitLine(linePositionMapperFactory, text, tabSize, wrappingColumn, columnsForFullWidthChar, wrappingIndent, isVisible) {\n var positionMapper = linePositionMapperFactory.createLineMapping(text, tabSize, wrappingColumn, columnsForFullWidthChar, wrappingIndent);\n if (positionMapper === null) {\n // No mapping needed\n if (isVisible) {\n return VisibleIdentitySplitLine.INSTANCE;\n }\n return InvisibleIdentitySplitLine.INSTANCE;\n }\n else {\n return new SplitLine(positionMapper, isVisible);\n }\n}\nvar IdentityCoordinatesConverter = /** @class */ (function () {\n function IdentityCoordinatesConverter(lines) {\n this._lines = lines;\n }\n IdentityCoordinatesConverter.prototype._validPosition = function (pos) {\n return this._lines.model.validatePosition(pos);\n };\n IdentityCoordinatesConverter.prototype._validRange = function (range) {\n return this._lines.model.validateRange(range);\n };\n // View -> Model conversion and related methods\n IdentityCoordinatesConverter.prototype.convertViewPositionToModelPosition = function (viewPosition) {\n return this._validPosition(viewPosition);\n };\n IdentityCoordinatesConverter.prototype.convertViewRangeToModelRange = function (viewRange) {\n return this._validRange(viewRange);\n };\n IdentityCoordinatesConverter.prototype.validateViewPosition = function (_viewPosition, expectedModelPosition) {\n return this._validPosition(expectedModelPosition);\n };\n IdentityCoordinatesConverter.prototype.validateViewRange = function (_viewRange, expectedModelRange) {\n return this._validRange(expectedModelRange);\n };\n // Model -> View conversion and related methods\n IdentityCoordinatesConverter.prototype.convertModelPositionToViewPosition = function (modelPosition) {\n return this._validPosition(modelPosition);\n };\n IdentityCoordinatesConverter.prototype.convertModelRangeToViewRange = function (modelRange) {\n return this._validRange(modelRange);\n };\n IdentityCoordinatesConverter.prototype.modelPositionIsVisible = function (modelPosition) {\n var lineCount = this._lines.model.getLineCount();\n if (modelPosition.lineNumber < 1 || modelPosition.lineNumber > lineCount) {\n // invalid arguments\n return false;\n }\n return true;\n };\n return IdentityCoordinatesConverter;\n}());\nexport { IdentityCoordinatesConverter };\nvar IdentityLinesCollection = /** @class */ (function () {\n function IdentityLinesCollection(model) {\n this.model = model;\n }\n IdentityLinesCollection.prototype.dispose = function () {\n };\n IdentityLinesCollection.prototype.createCoordinatesConverter = function () {\n return new IdentityCoordinatesConverter(this);\n };\n IdentityLinesCollection.prototype.getHiddenAreas = function () {\n return [];\n };\n IdentityLinesCollection.prototype.setHiddenAreas = function (_ranges) {\n return false;\n };\n IdentityLinesCollection.prototype.setTabSize = function (_newTabSize) {\n return false;\n };\n IdentityLinesCollection.prototype.setWrappingSettings = function (_wrappingIndent, _wrappingColumn, _columnsForFullWidthChar) {\n return false;\n };\n IdentityLinesCollection.prototype.onModelFlushed = function () {\n };\n IdentityLinesCollection.prototype.onModelLinesDeleted = function (_versionId, fromLineNumber, toLineNumber) {\n return new viewEvents.ViewLinesDeletedEvent(fromLineNumber, toLineNumber);\n };\n IdentityLinesCollection.prototype.onModelLinesInserted = function (_versionId, fromLineNumber, toLineNumber, _text) {\n return new viewEvents.ViewLinesInsertedEvent(fromLineNumber, toLineNumber);\n };\n IdentityLinesCollection.prototype.onModelLineChanged = function (_versionId, lineNumber, _newText) {\n return [false, new viewEvents.ViewLinesChangedEvent(lineNumber, lineNumber), null, null];\n };\n IdentityLinesCollection.prototype.acceptVersionId = function (_versionId) {\n };\n IdentityLinesCollection.prototype.getViewLineCount = function () {\n return this.model.getLineCount();\n };\n IdentityLinesCollection.prototype.warmUpLookupCache = function (_viewStartLineNumber, _viewEndLineNumber) {\n };\n IdentityLinesCollection.prototype.getActiveIndentGuide = function (viewLineNumber, _minLineNumber, _maxLineNumber) {\n return {\n startLineNumber: viewLineNumber,\n endLineNumber: viewLineNumber,\n indent: 0\n };\n };\n IdentityLinesCollection.prototype.getViewLinesIndentGuides = function (viewStartLineNumber, viewEndLineNumber) {\n var viewLineCount = viewEndLineNumber - viewStartLineNumber + 1;\n var result = new Array(viewLineCount);\n for (var i = 0; i < viewLineCount; i++) {\n result[i] = 0;\n }\n return result;\n };\n IdentityLinesCollection.prototype.getViewLineContent = function (viewLineNumber) {\n return this.model.getLineContent(viewLineNumber);\n };\n IdentityLinesCollection.prototype.getViewLineLength = function (viewLineNumber) {\n return this.model.getLineLength(viewLineNumber);\n };\n IdentityLinesCollection.prototype.getViewLineMinColumn = function (viewLineNumber) {\n return this.model.getLineMinColumn(viewLineNumber);\n };\n IdentityLinesCollection.prototype.getViewLineMaxColumn = function (viewLineNumber) {\n return this.model.getLineMaxColumn(viewLineNumber);\n };\n IdentityLinesCollection.prototype.getViewLineData = function (viewLineNumber) {\n var lineTokens = this.model.getLineTokens(viewLineNumber);\n var lineContent = lineTokens.getLineContent();\n return new ViewLineData(lineContent, false, 1, lineContent.length + 1, lineTokens.inflate());\n };\n IdentityLinesCollection.prototype.getViewLinesData = function (viewStartLineNumber, viewEndLineNumber, needed) {\n var lineCount = this.model.getLineCount();\n viewStartLineNumber = Math.min(Math.max(1, viewStartLineNumber), lineCount);\n viewEndLineNumber = Math.min(Math.max(1, viewEndLineNumber), lineCount);\n var result = [];\n for (var lineNumber = viewStartLineNumber; lineNumber <= viewEndLineNumber; lineNumber++) {\n var idx = lineNumber - viewStartLineNumber;\n if (!needed[idx]) {\n result[idx] = null;\n }\n result[idx] = this.getViewLineData(lineNumber);\n }\n return result;\n };\n IdentityLinesCollection.prototype.getAllOverviewRulerDecorations = function (ownerId, filterOutValidation, theme) {\n var decorations = this.model.getOverviewRulerDecorations(ownerId, filterOutValidation);\n var result = new OverviewRulerDecorations();\n for (var _i = 0, decorations_2 = decorations; _i < decorations_2.length; _i++) {\n var decoration = decorations_2[_i];\n var opts = decoration.options.overviewRuler;\n var lane = opts ? opts.position : 0;\n if (lane === 0) {\n continue;\n }\n var color = opts.getColor(theme);\n var viewStartLineNumber = decoration.range.startLineNumber;\n var viewEndLineNumber = decoration.range.endLineNumber;\n result.accept(color, viewStartLineNumber, viewEndLineNumber, lane);\n }\n return result.result;\n };\n IdentityLinesCollection.prototype.getDecorationsInRange = function (range, ownerId, filterOutValidation) {\n return this.model.getDecorationsInRange(range, ownerId, filterOutValidation);\n };\n return IdentityLinesCollection;\n}());\nexport { IdentityLinesCollection };\nvar OverviewRulerDecorations = /** @class */ (function () {\n function OverviewRulerDecorations() {\n this.result = Object.create(null);\n }\n OverviewRulerDecorations.prototype.accept = function (color, startLineNumber, endLineNumber, lane) {\n var prev = this.result[color];\n if (prev) {\n var prevLane = prev[prev.length - 3];\n var prevEndLineNumber = prev[prev.length - 1];\n if (prevLane === lane && prevEndLineNumber + 1 >= startLineNumber) {\n // merge into prev\n if (endLineNumber > prevEndLineNumber) {\n prev[prev.length - 1] = endLineNumber;\n }\n return;\n }\n // push\n prev.push(lane, startLineNumber, endLineNumber);\n }\n else {\n this.result[color] = [lane, startLineNumber, endLineNumber];\n }\n };\n return OverviewRulerDecorations;\n}());\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport * as strings from '../../../base/common/strings.js';\nimport { CharacterClassifier } from '../core/characterClassifier.js';\nimport { toUint32Array } from '../core/uint.js';\nimport { PrefixSumComputer } from './prefixSumComputer.js';\nimport { OutputPosition } from './splitLinesCollection.js';\nvar WrappingCharacterClassifier = /** @class */ (function (_super) {\n __extends(WrappingCharacterClassifier, _super);\n function WrappingCharacterClassifier(BREAK_BEFORE, BREAK_AFTER, BREAK_OBTRUSIVE) {\n var _this = _super.call(this, 0 /* NONE */) || this;\n for (var i = 0; i < BREAK_BEFORE.length; i++) {\n _this.set(BREAK_BEFORE.charCodeAt(i), 1 /* BREAK_BEFORE */);\n }\n for (var i = 0; i < BREAK_AFTER.length; i++) {\n _this.set(BREAK_AFTER.charCodeAt(i), 2 /* BREAK_AFTER */);\n }\n for (var i = 0; i < BREAK_OBTRUSIVE.length; i++) {\n _this.set(BREAK_OBTRUSIVE.charCodeAt(i), 3 /* BREAK_OBTRUSIVE */);\n }\n return _this;\n }\n WrappingCharacterClassifier.prototype.get = function (charCode) {\n // Initialize CharacterClass.BREAK_IDEOGRAPHIC for these Unicode ranges:\n // 1. CJK Unified Ideographs (0x4E00 -- 0x9FFF)\n // 2. CJK Unified Ideographs Extension A (0x3400 -- 0x4DBF)\n // 3. Hiragana and Katakana (0x3040 -- 0x30FF)\n if ((charCode >= 0x3040 && charCode <= 0x30FF)\n || (charCode >= 0x3400 && charCode <= 0x4DBF)\n || (charCode >= 0x4E00 && charCode <= 0x9FFF)) {\n return 4 /* BREAK_IDEOGRAPHIC */;\n }\n return _super.prototype.get.call(this, charCode);\n };\n return WrappingCharacterClassifier;\n}(CharacterClassifier));\nvar CharacterHardWrappingLineMapperFactory = /** @class */ (function () {\n function CharacterHardWrappingLineMapperFactory(breakBeforeChars, breakAfterChars, breakObtrusiveChars) {\n this.classifier = new WrappingCharacterClassifier(breakBeforeChars, breakAfterChars, breakObtrusiveChars);\n }\n // TODO@Alex -> duplicated in lineCommentCommand\n CharacterHardWrappingLineMapperFactory.nextVisibleColumn = function (currentVisibleColumn, tabSize, isTab, columnSize) {\n currentVisibleColumn = +currentVisibleColumn; //@perf\n tabSize = +tabSize; //@perf\n columnSize = +columnSize; //@perf\n if (isTab) {\n return currentVisibleColumn + (tabSize - (currentVisibleColumn % tabSize));\n }\n return currentVisibleColumn + columnSize;\n };\n CharacterHardWrappingLineMapperFactory.prototype.createLineMapping = function (lineText, tabSize, breakingColumn, columnsForFullWidthChar, hardWrappingIndent) {\n if (breakingColumn === -1) {\n return null;\n }\n tabSize = +tabSize; //@perf\n breakingColumn = +breakingColumn; //@perf\n columnsForFullWidthChar = +columnsForFullWidthChar; //@perf\n hardWrappingIndent = +hardWrappingIndent; //@perf\n var wrappedTextIndentVisibleColumn = 0;\n var wrappedTextIndent = '';\n var firstNonWhitespaceIndex = -1;\n if (hardWrappingIndent !== 0 /* None */) {\n firstNonWhitespaceIndex = strings.firstNonWhitespaceIndex(lineText);\n if (firstNonWhitespaceIndex !== -1) {\n // Track existing indent\n wrappedTextIndent = lineText.substring(0, firstNonWhitespaceIndex);\n for (var i = 0; i < firstNonWhitespaceIndex; i++) {\n wrappedTextIndentVisibleColumn = CharacterHardWrappingLineMapperFactory.nextVisibleColumn(wrappedTextIndentVisibleColumn, tabSize, lineText.charCodeAt(i) === 9 /* Tab */, 1);\n }\n // Increase indent of continuation lines, if desired\n var numberOfAdditionalTabs = 0;\n if (hardWrappingIndent === 2 /* Indent */) {\n numberOfAdditionalTabs = 1;\n }\n else if (hardWrappingIndent === 3 /* DeepIndent */) {\n numberOfAdditionalTabs = 2;\n }\n for (var i = 0; i < numberOfAdditionalTabs; i++) {\n wrappedTextIndent += '\\t';\n wrappedTextIndentVisibleColumn = CharacterHardWrappingLineMapperFactory.nextVisibleColumn(wrappedTextIndentVisibleColumn, tabSize, true, 1);\n }\n // Force sticking to beginning of line if no character would fit except for the indentation\n if (wrappedTextIndentVisibleColumn + columnsForFullWidthChar > breakingColumn) {\n wrappedTextIndent = '';\n wrappedTextIndentVisibleColumn = 0;\n }\n }\n }\n var classifier = this.classifier;\n var lastBreakingOffset = 0; // Last 0-based offset in the lineText at which a break happened\n var breakingLengths = []; // The length of each broken-up line text\n var breakingLengthsIndex = 0; // The count of breaks already done\n var visibleColumn = 0; // Visible column since the beginning of the current line\n var niceBreakOffset = -1; // Last index of a character that indicates a break should happen before it (more desirable)\n var niceBreakVisibleColumn = 0; // visible column if a break were to be later introduced before `niceBreakOffset`\n var obtrusiveBreakOffset = -1; // Last index of a character that indicates a break should happen before it (less desirable)\n var obtrusiveBreakVisibleColumn = 0; // visible column if a break were to be later introduced before `obtrusiveBreakOffset`\n var len = lineText.length;\n for (var i = 0; i < len; i++) {\n // At this point, there is a certainty that the character before `i` fits on the current line,\n // but the character at `i` might not fit\n var charCode = lineText.charCodeAt(i);\n var charCodeIsTab = (charCode === 9 /* Tab */);\n var charCodeClass = classifier.get(charCode);\n if (charCodeClass === 1 /* BREAK_BEFORE */) {\n // This is a character that indicates that a break should happen before it\n // Since we are certain the character before `i` fits, there's no extra checking needed,\n // just mark it as a nice breaking opportunity\n niceBreakOffset = i;\n niceBreakVisibleColumn = wrappedTextIndentVisibleColumn;\n }\n // CJK breaking : before break\n if (charCodeClass === 4 /* BREAK_IDEOGRAPHIC */ && i > 0) {\n var prevCode = lineText.charCodeAt(i - 1);\n var prevClass = classifier.get(prevCode);\n if (prevClass !== 1 /* BREAK_BEFORE */) { // Kinsoku Shori: Don't break after a leading character, like an open bracket\n niceBreakOffset = i;\n niceBreakVisibleColumn = wrappedTextIndentVisibleColumn;\n }\n }\n var charColumnSize = 1;\n if (strings.isFullWidthCharacter(charCode)) {\n charColumnSize = columnsForFullWidthChar;\n }\n // Advance visibleColumn with character at `i`\n visibleColumn = CharacterHardWrappingLineMapperFactory.nextVisibleColumn(visibleColumn, tabSize, charCodeIsTab, charColumnSize);\n if (visibleColumn > breakingColumn && i !== 0) {\n // We need to break at least before character at `i`:\n // - break before niceBreakLastOffset if it exists (and re-establish a correct visibleColumn by using niceBreakVisibleColumn + charAt(i))\n // - otherwise, break before obtrusiveBreakLastOffset if it exists (and re-establish a correct visibleColumn by using obtrusiveBreakVisibleColumn + charAt(i))\n // - otherwise, break before i (and re-establish a correct visibleColumn by charAt(i))\n var breakBeforeOffset = void 0;\n var restoreVisibleColumnFrom = void 0;\n if (niceBreakOffset !== -1 && niceBreakVisibleColumn <= breakingColumn) {\n // We will break before `niceBreakLastOffset`\n breakBeforeOffset = niceBreakOffset;\n restoreVisibleColumnFrom = niceBreakVisibleColumn;\n }\n else if (obtrusiveBreakOffset !== -1 && obtrusiveBreakVisibleColumn <= breakingColumn) {\n // We will break before `obtrusiveBreakLastOffset`\n breakBeforeOffset = obtrusiveBreakOffset;\n restoreVisibleColumnFrom = obtrusiveBreakVisibleColumn;\n }\n else {\n // We will break before `i`\n breakBeforeOffset = i;\n restoreVisibleColumnFrom = wrappedTextIndentVisibleColumn;\n }\n // Break before character at `breakBeforeOffset`\n breakingLengths[breakingLengthsIndex++] = breakBeforeOffset - lastBreakingOffset;\n lastBreakingOffset = breakBeforeOffset;\n // Re-establish visibleColumn by taking character at `i` into account\n visibleColumn = CharacterHardWrappingLineMapperFactory.nextVisibleColumn(restoreVisibleColumnFrom, tabSize, charCodeIsTab, charColumnSize);\n // Reset markers\n niceBreakOffset = -1;\n niceBreakVisibleColumn = 0;\n obtrusiveBreakOffset = -1;\n obtrusiveBreakVisibleColumn = 0;\n }\n // At this point, there is a certainty that the character at `i` fits on the current line\n if (niceBreakOffset !== -1) {\n // Advance niceBreakVisibleColumn\n niceBreakVisibleColumn = CharacterHardWrappingLineMapperFactory.nextVisibleColumn(niceBreakVisibleColumn, tabSize, charCodeIsTab, charColumnSize);\n }\n if (obtrusiveBreakOffset !== -1) {\n // Advance obtrusiveBreakVisibleColumn\n obtrusiveBreakVisibleColumn = CharacterHardWrappingLineMapperFactory.nextVisibleColumn(obtrusiveBreakVisibleColumn, tabSize, charCodeIsTab, charColumnSize);\n }\n if (charCodeClass === 2 /* BREAK_AFTER */ && (hardWrappingIndent === 0 /* None */ || i >= firstNonWhitespaceIndex)) {\n // This is a character that indicates that a break should happen after it\n niceBreakOffset = i + 1;\n niceBreakVisibleColumn = wrappedTextIndentVisibleColumn;\n }\n // CJK breaking : after break\n if (charCodeClass === 4 /* BREAK_IDEOGRAPHIC */ && i < len - 1) {\n var nextCode = lineText.charCodeAt(i + 1);\n var nextClass = classifier.get(nextCode);\n if (nextClass !== 2 /* BREAK_AFTER */) { // Kinsoku Shori: Don't break before a trailing character, like a period\n niceBreakOffset = i + 1;\n niceBreakVisibleColumn = wrappedTextIndentVisibleColumn;\n }\n }\n if (charCodeClass === 3 /* BREAK_OBTRUSIVE */) {\n // This is an obtrusive character that indicates that a break should happen after it\n obtrusiveBreakOffset = i + 1;\n obtrusiveBreakVisibleColumn = wrappedTextIndentVisibleColumn;\n }\n }\n if (breakingLengthsIndex === 0) {\n return null;\n }\n // Add last segment\n breakingLengths[breakingLengthsIndex++] = len - lastBreakingOffset;\n return new CharacterHardWrappingLineMapping(new PrefixSumComputer(toUint32Array(breakingLengths)), wrappedTextIndent);\n };\n return CharacterHardWrappingLineMapperFactory;\n}());\nexport { CharacterHardWrappingLineMapperFactory };\nvar CharacterHardWrappingLineMapping = /** @class */ (function () {\n function CharacterHardWrappingLineMapping(prefixSums, wrappedLinesIndent) {\n this._prefixSums = prefixSums;\n this._wrappedLinesIndent = wrappedLinesIndent;\n }\n CharacterHardWrappingLineMapping.prototype.getOutputLineCount = function () {\n return this._prefixSums.getCount();\n };\n CharacterHardWrappingLineMapping.prototype.getWrappedLinesIndent = function () {\n return this._wrappedLinesIndent;\n };\n CharacterHardWrappingLineMapping.prototype.getInputOffsetOfOutputPosition = function (outputLineIndex, outputOffset) {\n if (outputLineIndex === 0) {\n return outputOffset;\n }\n else {\n return this._prefixSums.getAccumulatedValue(outputLineIndex - 1) + outputOffset;\n }\n };\n CharacterHardWrappingLineMapping.prototype.getOutputPositionOfInputOffset = function (inputOffset) {\n var r = this._prefixSums.getIndexOf(inputOffset);\n return new OutputPosition(r.index, r.remainder);\n };\n return CharacterHardWrappingLineMapping;\n}());\nexport { CharacterHardWrappingLineMapping };\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport { Position } from '../core/position.js';\nimport { Range } from '../core/range.js';\nimport { InlineDecoration, ViewModelDecoration } from './viewModel.js';\nvar ViewModelDecorations = /** @class */ (function () {\n function ViewModelDecorations(editorId, model, configuration, linesCollection, coordinatesConverter) {\n this.editorId = editorId;\n this.model = model;\n this.configuration = configuration;\n this._linesCollection = linesCollection;\n this._coordinatesConverter = coordinatesConverter;\n this._decorationsCache = Object.create(null);\n this._clearCachedModelDecorationsResolver();\n }\n ViewModelDecorations.prototype._clearCachedModelDecorationsResolver = function () {\n this._cachedModelDecorationsResolver = null;\n this._cachedModelDecorationsResolverViewRange = null;\n };\n ViewModelDecorations.prototype.dispose = function () {\n this._decorationsCache = Object.create(null);\n this._clearCachedModelDecorationsResolver();\n };\n ViewModelDecorations.prototype.reset = function () {\n this._decorationsCache = Object.create(null);\n this._clearCachedModelDecorationsResolver();\n };\n ViewModelDecorations.prototype.onModelDecorationsChanged = function () {\n this._decorationsCache = Object.create(null);\n this._clearCachedModelDecorationsResolver();\n };\n ViewModelDecorations.prototype.onLineMappingChanged = function () {\n this._decorationsCache = Object.create(null);\n this._clearCachedModelDecorationsResolver();\n };\n ViewModelDecorations.prototype._getOrCreateViewModelDecoration = function (modelDecoration) {\n var id = modelDecoration.id;\n var r = this._decorationsCache[id];\n if (!r) {\n var modelRange = modelDecoration.range;\n var options = modelDecoration.options;\n var viewRange = void 0;\n if (options.isWholeLine) {\n var start = this._coordinatesConverter.convertModelPositionToViewPosition(new Position(modelRange.startLineNumber, 1));\n var end = this._coordinatesConverter.convertModelPositionToViewPosition(new Position(modelRange.endLineNumber, this.model.getLineMaxColumn(modelRange.endLineNumber)));\n viewRange = new Range(start.lineNumber, start.column, end.lineNumber, end.column);\n }\n else {\n viewRange = this._coordinatesConverter.convertModelRangeToViewRange(modelRange);\n }\n r = new ViewModelDecoration(viewRange, options);\n this._decorationsCache[id] = r;\n }\n return r;\n };\n ViewModelDecorations.prototype.getDecorationsViewportData = function (viewRange) {\n var cacheIsValid = (this._cachedModelDecorationsResolver !== null);\n cacheIsValid = cacheIsValid && (viewRange.equalsRange(this._cachedModelDecorationsResolverViewRange));\n if (!cacheIsValid) {\n this._cachedModelDecorationsResolver = this._getDecorationsViewportData(viewRange);\n this._cachedModelDecorationsResolverViewRange = viewRange;\n }\n return this._cachedModelDecorationsResolver;\n };\n ViewModelDecorations.prototype._getDecorationsViewportData = function (viewportRange) {\n var modelDecorations = this._linesCollection.getDecorationsInRange(viewportRange, this.editorId, this.configuration.editor.readOnly);\n var startLineNumber = viewportRange.startLineNumber;\n var endLineNumber = viewportRange.endLineNumber;\n var decorationsInViewport = [], decorationsInViewportLen = 0;\n var inlineDecorations = [];\n for (var j = startLineNumber; j <= endLineNumber; j++) {\n inlineDecorations[j - startLineNumber] = [];\n }\n for (var i = 0, len = modelDecorations.length; i < len; i++) {\n var modelDecoration = modelDecorations[i];\n var decorationOptions = modelDecoration.options;\n var viewModelDecoration = this._getOrCreateViewModelDecoration(modelDecoration);\n var viewRange = viewModelDecoration.range;\n decorationsInViewport[decorationsInViewportLen++] = viewModelDecoration;\n if (decorationOptions.inlineClassName) {\n var inlineDecoration = new InlineDecoration(viewRange, decorationOptions.inlineClassName, decorationOptions.inlineClassNameAffectsLetterSpacing ? 3 /* RegularAffectingLetterSpacing */ : 0 /* Regular */);\n var intersectedStartLineNumber = Math.max(startLineNumber, viewRange.startLineNumber);\n var intersectedEndLineNumber = Math.min(endLineNumber, viewRange.endLineNumber);\n for (var j = intersectedStartLineNumber; j <= intersectedEndLineNumber; j++) {\n inlineDecorations[j - startLineNumber].push(inlineDecoration);\n }\n }\n if (decorationOptions.beforeContentClassName) {\n if (startLineNumber <= viewRange.startLineNumber && viewRange.startLineNumber <= endLineNumber) {\n var inlineDecoration = new InlineDecoration(new Range(viewRange.startLineNumber, viewRange.startColumn, viewRange.startLineNumber, viewRange.startColumn), decorationOptions.beforeContentClassName, 1 /* Before */);\n inlineDecorations[viewRange.startLineNumber - startLineNumber].push(inlineDecoration);\n }\n }\n if (decorationOptions.afterContentClassName) {\n if (startLineNumber <= viewRange.endLineNumber && viewRange.endLineNumber <= endLineNumber) {\n var inlineDecoration = new InlineDecoration(new Range(viewRange.endLineNumber, viewRange.endColumn, viewRange.endLineNumber, viewRange.endColumn), decorationOptions.afterContentClassName, 2 /* After */);\n inlineDecorations[viewRange.endLineNumber - startLineNumber].push(inlineDecoration);\n }\n }\n }\n return {\n decorations: decorationsInViewport,\n inlineDecorations: inlineDecorations\n };\n };\n return ViewModelDecorations;\n}());\nexport { ViewModelDecorations };\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { Color } from '../../../base/common/color.js';\nimport * as strings from '../../../base/common/strings.js';\nimport { Position } from '../core/position.js';\nimport { Range } from '../core/range.js';\nimport { TokenizationRegistry } from '../modes.js';\nimport { tokenizeLineToHTML } from '../modes/textToHtmlTokenizer.js';\nimport { MinimapTokensColorTracker } from '../view/minimapCharRenderer.js';\nimport * as viewEvents from '../view/viewEvents.js';\nimport { ViewLayout } from '../viewLayout/viewLayout.js';\nimport { CharacterHardWrappingLineMapperFactory } from './characterHardWrappingLineMapper.js';\nimport { IdentityLinesCollection, SplitLinesCollection } from './splitLinesCollection.js';\nimport { MinimapLinesRenderingData, ViewLineRenderingData } from './viewModel.js';\nimport { ViewModelDecorations } from './viewModelDecorations.js';\nimport { RunOnceScheduler } from '../../../base/common/async.js';\nvar USE_IDENTITY_LINES_COLLECTION = true;\nvar ViewModel = /** @class */ (function (_super) {\n __extends(ViewModel, _super);\n function ViewModel(editorId, configuration, model, scheduleAtNextAnimationFrame) {\n var _this = _super.call(this) || this;\n _this.editorId = editorId;\n _this.configuration = configuration;\n _this.model = model;\n _this._tokenizeViewportSoon = _this._register(new RunOnceScheduler(function () { return _this.tokenizeViewport(); }, 50));\n _this.hasFocus = false;\n _this.viewportStartLine = -1;\n _this.viewportStartLineTrackedRange = null;\n _this.viewportStartLineDelta = 0;\n if (USE_IDENTITY_LINES_COLLECTION && _this.model.isTooLargeForTokenization()) {\n _this.lines = new IdentityLinesCollection(_this.model);\n }\n else {\n var conf = _this.configuration.editor;\n var hardWrappingLineMapperFactory = new CharacterHardWrappingLineMapperFactory(conf.wrappingInfo.wordWrapBreakBeforeCharacters, conf.wrappingInfo.wordWrapBreakAfterCharacters, conf.wrappingInfo.wordWrapBreakObtrusiveCharacters);\n _this.lines = new SplitLinesCollection(_this.model, hardWrappingLineMapperFactory, _this.model.getOptions().tabSize, conf.wrappingInfo.wrappingColumn, conf.fontInfo.typicalFullwidthCharacterWidth / conf.fontInfo.typicalHalfwidthCharacterWidth, conf.wrappingInfo.wrappingIndent);\n }\n _this.coordinatesConverter = _this.lines.createCoordinatesConverter();\n _this.viewLayout = _this._register(new ViewLayout(_this.configuration, _this.getLineCount(), scheduleAtNextAnimationFrame));\n _this._register(_this.viewLayout.onDidScroll(function (e) {\n if (e.scrollTopChanged) {\n _this._tokenizeViewportSoon.schedule();\n }\n try {\n var eventsCollector = _this._beginEmit();\n eventsCollector.emit(new viewEvents.ViewScrollChangedEvent(e));\n }\n finally {\n _this._endEmit();\n }\n }));\n _this.decorations = new ViewModelDecorations(_this.editorId, _this.model, _this.configuration, _this.lines, _this.coordinatesConverter);\n _this._registerModelEvents();\n _this._register(_this.configuration.onDidChange(function (e) {\n try {\n var eventsCollector = _this._beginEmit();\n _this._onConfigurationChanged(eventsCollector, e);\n }\n finally {\n _this._endEmit();\n }\n }));\n _this._register(MinimapTokensColorTracker.getInstance().onDidChange(function () {\n try {\n var eventsCollector = _this._beginEmit();\n eventsCollector.emit(new viewEvents.ViewTokensColorsChangedEvent());\n }\n finally {\n _this._endEmit();\n }\n }));\n return _this;\n }\n ViewModel.prototype.dispose = function () {\n // First remove listeners, as disposing the lines might end up sending\n // model decoration changed events ... and we no longer care about them ...\n _super.prototype.dispose.call(this);\n this.decorations.dispose();\n this.lines.dispose();\n this.viewportStartLineTrackedRange = this.model._setTrackedRange(this.viewportStartLineTrackedRange, null, 1 /* NeverGrowsWhenTypingAtEdges */);\n };\n ViewModel.prototype.tokenizeViewport = function () {\n var linesViewportData = this.viewLayout.getLinesViewportData();\n var startPosition = this.coordinatesConverter.convertViewPositionToModelPosition(new Position(linesViewportData.startLineNumber, 1));\n var endPosition = this.coordinatesConverter.convertViewPositionToModelPosition(new Position(linesViewportData.endLineNumber, 1));\n this.model.tokenizeViewport(startPosition.lineNumber, endPosition.lineNumber);\n };\n ViewModel.prototype.setHasFocus = function (hasFocus) {\n this.hasFocus = hasFocus;\n };\n ViewModel.prototype._onConfigurationChanged = function (eventsCollector, e) {\n // We might need to restore the current centered view range, so save it (if available)\n var previousViewportStartModelPosition = null;\n if (this.viewportStartLine !== -1) {\n var previousViewportStartViewPosition = new Position(this.viewportStartLine, this.getLineMinColumn(this.viewportStartLine));\n previousViewportStartModelPosition = this.coordinatesConverter.convertViewPositionToModelPosition(previousViewportStartViewPosition);\n }\n var restorePreviousViewportStart = false;\n var conf = this.configuration.editor;\n if (this.lines.setWrappingSettings(conf.wrappingInfo.wrappingIndent, conf.wrappingInfo.wrappingColumn, conf.fontInfo.typicalFullwidthCharacterWidth / conf.fontInfo.typicalHalfwidthCharacterWidth)) {\n eventsCollector.emit(new viewEvents.ViewFlushedEvent());\n eventsCollector.emit(new viewEvents.ViewLineMappingChangedEvent());\n eventsCollector.emit(new viewEvents.ViewDecorationsChangedEvent());\n this.decorations.onLineMappingChanged();\n this.viewLayout.onFlushed(this.getLineCount());\n if (this.viewLayout.getCurrentScrollTop() !== 0) {\n // Never change the scroll position from 0 to something else...\n restorePreviousViewportStart = true;\n }\n }\n if (e.readOnly) {\n // Must read again all decorations due to readOnly filtering\n this.decorations.reset();\n eventsCollector.emit(new viewEvents.ViewDecorationsChangedEvent());\n }\n eventsCollector.emit(new viewEvents.ViewConfigurationChangedEvent(e));\n this.viewLayout.onConfigurationChanged(e);\n if (restorePreviousViewportStart && previousViewportStartModelPosition) {\n var viewPosition = this.coordinatesConverter.convertModelPositionToViewPosition(previousViewportStartModelPosition);\n var viewPositionTop = this.viewLayout.getVerticalOffsetForLineNumber(viewPosition.lineNumber);\n this.viewLayout.setScrollPositionNow({ scrollTop: viewPositionTop + this.viewportStartLineDelta });\n }\n };\n ViewModel.prototype._registerModelEvents = function () {\n var _this = this;\n this._register(this.model.onDidChangeRawContentFast(function (e) {\n try {\n var eventsCollector = _this._beginEmit();\n var hadOtherModelChange = false;\n var hadModelLineChangeThatChangedLineMapping = false;\n var changes = e.changes;\n var versionId = e.versionId;\n for (var j = 0, lenJ = changes.length; j < lenJ; j++) {\n var change = changes[j];\n switch (change.changeType) {\n case 1 /* Flush */: {\n _this.lines.onModelFlushed();\n eventsCollector.emit(new viewEvents.ViewFlushedEvent());\n _this.decorations.reset();\n _this.viewLayout.onFlushed(_this.getLineCount());\n hadOtherModelChange = true;\n break;\n }\n case 3 /* LinesDeleted */: {\n var linesDeletedEvent = _this.lines.onModelLinesDeleted(versionId, change.fromLineNumber, change.toLineNumber);\n if (linesDeletedEvent !== null) {\n eventsCollector.emit(linesDeletedEvent);\n _this.viewLayout.onLinesDeleted(linesDeletedEvent.fromLineNumber, linesDeletedEvent.toLineNumber);\n }\n hadOtherModelChange = true;\n break;\n }\n case 4 /* LinesInserted */: {\n var linesInsertedEvent = _this.lines.onModelLinesInserted(versionId, change.fromLineNumber, change.toLineNumber, change.detail);\n if (linesInsertedEvent !== null) {\n eventsCollector.emit(linesInsertedEvent);\n _this.viewLayout.onLinesInserted(linesInsertedEvent.fromLineNumber, linesInsertedEvent.toLineNumber);\n }\n hadOtherModelChange = true;\n break;\n }\n case 2 /* LineChanged */: {\n var _a = _this.lines.onModelLineChanged(versionId, change.lineNumber, change.detail), lineMappingChanged = _a[0], linesChangedEvent = _a[1], linesInsertedEvent = _a[2], linesDeletedEvent = _a[3];\n hadModelLineChangeThatChangedLineMapping = lineMappingChanged;\n if (linesChangedEvent) {\n eventsCollector.emit(linesChangedEvent);\n }\n if (linesInsertedEvent) {\n eventsCollector.emit(linesInsertedEvent);\n _this.viewLayout.onLinesInserted(linesInsertedEvent.fromLineNumber, linesInsertedEvent.toLineNumber);\n }\n if (linesDeletedEvent) {\n eventsCollector.emit(linesDeletedEvent);\n _this.viewLayout.onLinesDeleted(linesDeletedEvent.fromLineNumber, linesDeletedEvent.toLineNumber);\n }\n break;\n }\n case 5 /* EOLChanged */: {\n // Nothing to do. The new version will be accepted below\n break;\n }\n }\n }\n _this.lines.acceptVersionId(versionId);\n _this.viewLayout.onHeightMaybeChanged();\n if (!hadOtherModelChange && hadModelLineChangeThatChangedLineMapping) {\n eventsCollector.emit(new viewEvents.ViewLineMappingChangedEvent());\n eventsCollector.emit(new viewEvents.ViewDecorationsChangedEvent());\n _this.decorations.onLineMappingChanged();\n }\n }\n finally {\n _this._endEmit();\n }\n // Update the configuration and reset the centered view line\n _this.viewportStartLine = -1;\n _this.configuration.setMaxLineNumber(_this.model.getLineCount());\n // Recover viewport\n if (!_this.hasFocus && _this.model.getAttachedEditorCount() >= 2 && _this.viewportStartLineTrackedRange) {\n var modelRange = _this.model._getTrackedRange(_this.viewportStartLineTrackedRange);\n if (modelRange) {\n var viewPosition = _this.coordinatesConverter.convertModelPositionToViewPosition(modelRange.getStartPosition());\n var viewPositionTop = _this.viewLayout.getVerticalOffsetForLineNumber(viewPosition.lineNumber);\n _this.viewLayout.setScrollPositionNow({ scrollTop: viewPositionTop + _this.viewportStartLineDelta });\n }\n }\n }));\n this._register(this.model.onDidChangeTokens(function (e) {\n var viewRanges = [];\n for (var j = 0, lenJ = e.ranges.length; j < lenJ; j++) {\n var modelRange = e.ranges[j];\n var viewStartLineNumber = _this.coordinatesConverter.convertModelPositionToViewPosition(new Position(modelRange.fromLineNumber, 1)).lineNumber;\n var viewEndLineNumber = _this.coordinatesConverter.convertModelPositionToViewPosition(new Position(modelRange.toLineNumber, _this.model.getLineMaxColumn(modelRange.toLineNumber))).lineNumber;\n viewRanges[j] = {\n fromLineNumber: viewStartLineNumber,\n toLineNumber: viewEndLineNumber\n };\n }\n try {\n var eventsCollector = _this._beginEmit();\n eventsCollector.emit(new viewEvents.ViewTokensChangedEvent(viewRanges));\n }\n finally {\n _this._endEmit();\n }\n if (e.tokenizationSupportChanged) {\n _this._tokenizeViewportSoon.schedule();\n }\n }));\n this._register(this.model.onDidChangeLanguageConfiguration(function (e) {\n try {\n var eventsCollector = _this._beginEmit();\n eventsCollector.emit(new viewEvents.ViewLanguageConfigurationEvent());\n }\n finally {\n _this._endEmit();\n }\n }));\n this._register(this.model.onDidChangeOptions(function (e) {\n // A tab size change causes a line mapping changed event => all view parts will repaint OK, no further event needed here\n if (_this.lines.setTabSize(_this.model.getOptions().tabSize)) {\n _this.decorations.onLineMappingChanged();\n _this.viewLayout.onFlushed(_this.getLineCount());\n try {\n var eventsCollector = _this._beginEmit();\n eventsCollector.emit(new viewEvents.ViewFlushedEvent());\n eventsCollector.emit(new viewEvents.ViewLineMappingChangedEvent());\n eventsCollector.emit(new viewEvents.ViewDecorationsChangedEvent());\n }\n finally {\n _this._endEmit();\n }\n }\n }));\n this._register(this.model.onDidChangeDecorations(function (e) {\n _this.decorations.onModelDecorationsChanged();\n try {\n var eventsCollector = _this._beginEmit();\n eventsCollector.emit(new viewEvents.ViewDecorationsChangedEvent());\n }\n finally {\n _this._endEmit();\n }\n }));\n };\n ViewModel.prototype.setHiddenAreas = function (ranges) {\n try {\n var eventsCollector = this._beginEmit();\n var lineMappingChanged = this.lines.setHiddenAreas(ranges);\n if (lineMappingChanged) {\n eventsCollector.emit(new viewEvents.ViewFlushedEvent());\n eventsCollector.emit(new viewEvents.ViewLineMappingChangedEvent());\n eventsCollector.emit(new viewEvents.ViewDecorationsChangedEvent());\n this.decorations.onLineMappingChanged();\n this.viewLayout.onFlushed(this.getLineCount());\n this.viewLayout.onHeightMaybeChanged();\n }\n }\n finally {\n this._endEmit();\n }\n };\n ViewModel.prototype.getVisibleRanges = function () {\n var visibleViewRange = this.getCompletelyVisibleViewRange();\n var visibleRange = this.coordinatesConverter.convertViewRangeToModelRange(visibleViewRange);\n var hiddenAreas = this.lines.getHiddenAreas();\n if (hiddenAreas.length === 0) {\n return [visibleRange];\n }\n var result = [], resultLen = 0;\n var startLineNumber = visibleRange.startLineNumber;\n var startColumn = visibleRange.startColumn;\n var endLineNumber = visibleRange.endLineNumber;\n var endColumn = visibleRange.endColumn;\n for (var i = 0, len = hiddenAreas.length; i < len; i++) {\n var hiddenStartLineNumber = hiddenAreas[i].startLineNumber;\n var hiddenEndLineNumber = hiddenAreas[i].endLineNumber;\n if (hiddenEndLineNumber < startLineNumber) {\n continue;\n }\n if (hiddenStartLineNumber > endLineNumber) {\n continue;\n }\n if (startLineNumber < hiddenStartLineNumber) {\n result[resultLen++] = new Range(startLineNumber, startColumn, hiddenStartLineNumber - 1, this.model.getLineMaxColumn(hiddenStartLineNumber - 1));\n }\n startLineNumber = hiddenEndLineNumber + 1;\n startColumn = 1;\n }\n if (startLineNumber < endLineNumber || (startLineNumber === endLineNumber && startColumn < endColumn)) {\n result[resultLen++] = new Range(startLineNumber, startColumn, endLineNumber, endColumn);\n }\n return result;\n };\n ViewModel.prototype.getCompletelyVisibleViewRange = function () {\n var partialData = this.viewLayout.getLinesViewportData();\n var startViewLineNumber = partialData.completelyVisibleStartLineNumber;\n var endViewLineNumber = partialData.completelyVisibleEndLineNumber;\n return new Range(startViewLineNumber, this.getLineMinColumn(startViewLineNumber), endViewLineNumber, this.getLineMaxColumn(endViewLineNumber));\n };\n ViewModel.prototype.getCompletelyVisibleViewRangeAtScrollTop = function (scrollTop) {\n var partialData = this.viewLayout.getLinesViewportDataAtScrollTop(scrollTop);\n var startViewLineNumber = partialData.completelyVisibleStartLineNumber;\n var endViewLineNumber = partialData.completelyVisibleEndLineNumber;\n return new Range(startViewLineNumber, this.getLineMinColumn(startViewLineNumber), endViewLineNumber, this.getLineMaxColumn(endViewLineNumber));\n };\n ViewModel.prototype.saveState = function () {\n var compatViewState = this.viewLayout.saveState();\n var scrollTop = compatViewState.scrollTop;\n var firstViewLineNumber = this.viewLayout.getLineNumberAtVerticalOffset(scrollTop);\n var firstPosition = this.coordinatesConverter.convertViewPositionToModelPosition(new Position(firstViewLineNumber, this.getLineMinColumn(firstViewLineNumber)));\n var firstPositionDeltaTop = this.viewLayout.getVerticalOffsetForLineNumber(firstViewLineNumber) - scrollTop;\n return {\n scrollLeft: compatViewState.scrollLeft,\n firstPosition: firstPosition,\n firstPositionDeltaTop: firstPositionDeltaTop\n };\n };\n ViewModel.prototype.reduceRestoreState = function (state) {\n if (typeof state.firstPosition === 'undefined') {\n // This is a view state serialized by an older version\n return this._reduceRestoreStateCompatibility(state);\n }\n var modelPosition = this.model.validatePosition(state.firstPosition);\n var viewPosition = this.coordinatesConverter.convertModelPositionToViewPosition(modelPosition);\n var scrollTop = this.viewLayout.getVerticalOffsetForLineNumber(viewPosition.lineNumber) - state.firstPositionDeltaTop;\n return {\n scrollLeft: state.scrollLeft,\n scrollTop: scrollTop\n };\n };\n ViewModel.prototype._reduceRestoreStateCompatibility = function (state) {\n return {\n scrollLeft: state.scrollLeft,\n scrollTop: state.scrollTopWithoutViewZones\n };\n };\n ViewModel.prototype.getTabSize = function () {\n return this.model.getOptions().tabSize;\n };\n ViewModel.prototype.getOptions = function () {\n return this.model.getOptions();\n };\n ViewModel.prototype.getLineCount = function () {\n return this.lines.getViewLineCount();\n };\n /**\n * Gives a hint that a lot of requests are about to come in for these line numbers.\n */\n ViewModel.prototype.setViewport = function (startLineNumber, endLineNumber, centeredLineNumber) {\n this.lines.warmUpLookupCache(startLineNumber, endLineNumber);\n this.viewportStartLine = startLineNumber;\n var position = this.coordinatesConverter.convertViewPositionToModelPosition(new Position(startLineNumber, this.getLineMinColumn(startLineNumber)));\n this.viewportStartLineTrackedRange = this.model._setTrackedRange(this.viewportStartLineTrackedRange, new Range(position.lineNumber, position.column, position.lineNumber, position.column), 1 /* NeverGrowsWhenTypingAtEdges */);\n var viewportStartLineTop = this.viewLayout.getVerticalOffsetForLineNumber(startLineNumber);\n var scrollTop = this.viewLayout.getCurrentScrollTop();\n this.viewportStartLineDelta = scrollTop - viewportStartLineTop;\n };\n ViewModel.prototype.getActiveIndentGuide = function (lineNumber, minLineNumber, maxLineNumber) {\n return this.lines.getActiveIndentGuide(lineNumber, minLineNumber, maxLineNumber);\n };\n ViewModel.prototype.getLinesIndentGuides = function (startLineNumber, endLineNumber) {\n return this.lines.getViewLinesIndentGuides(startLineNumber, endLineNumber);\n };\n ViewModel.prototype.getLineContent = function (lineNumber) {\n return this.lines.getViewLineContent(lineNumber);\n };\n ViewModel.prototype.getLineLength = function (lineNumber) {\n return this.lines.getViewLineLength(lineNumber);\n };\n ViewModel.prototype.getLineMinColumn = function (lineNumber) {\n return this.lines.getViewLineMinColumn(lineNumber);\n };\n ViewModel.prototype.getLineMaxColumn = function (lineNumber) {\n return this.lines.getViewLineMaxColumn(lineNumber);\n };\n ViewModel.prototype.getLineFirstNonWhitespaceColumn = function (lineNumber) {\n var result = strings.firstNonWhitespaceIndex(this.getLineContent(lineNumber));\n if (result === -1) {\n return 0;\n }\n return result + 1;\n };\n ViewModel.prototype.getLineLastNonWhitespaceColumn = function (lineNumber) {\n var result = strings.lastNonWhitespaceIndex(this.getLineContent(lineNumber));\n if (result === -1) {\n return 0;\n }\n return result + 2;\n };\n ViewModel.prototype.getDecorationsInViewport = function (visibleRange) {\n return this.decorations.getDecorationsViewportData(visibleRange).decorations;\n };\n ViewModel.prototype.getViewLineRenderingData = function (visibleRange, lineNumber) {\n var mightContainRTL = this.model.mightContainRTL();\n var mightContainNonBasicASCII = this.model.mightContainNonBasicASCII();\n var tabSize = this.getTabSize();\n var lineData = this.lines.getViewLineData(lineNumber);\n var allInlineDecorations = this.decorations.getDecorationsViewportData(visibleRange).inlineDecorations;\n var inlineDecorations = allInlineDecorations[lineNumber - visibleRange.startLineNumber];\n return new ViewLineRenderingData(lineData.minColumn, lineData.maxColumn, lineData.content, lineData.continuesWithWrappedLine, mightContainRTL, mightContainNonBasicASCII, lineData.tokens, inlineDecorations, tabSize);\n };\n ViewModel.prototype.getViewLineData = function (lineNumber) {\n return this.lines.getViewLineData(lineNumber);\n };\n ViewModel.prototype.getMinimapLinesRenderingData = function (startLineNumber, endLineNumber, needed) {\n var result = this.lines.getViewLinesData(startLineNumber, endLineNumber, needed);\n return new MinimapLinesRenderingData(this.getTabSize(), result);\n };\n ViewModel.prototype.getAllOverviewRulerDecorations = function (theme) {\n return this.lines.getAllOverviewRulerDecorations(this.editorId, this.configuration.editor.readOnly, theme);\n };\n ViewModel.prototype.invalidateOverviewRulerColorCache = function () {\n var decorations = this.model.getOverviewRulerDecorations();\n for (var _i = 0, decorations_1 = decorations; _i < decorations_1.length; _i++) {\n var decoration = decorations_1[_i];\n var opts = decoration.options.overviewRuler;\n if (opts) {\n opts.invalidateCachedColor();\n }\n }\n };\n ViewModel.prototype.getValueInRange = function (range, eol) {\n var modelRange = this.coordinatesConverter.convertViewRangeToModelRange(range);\n return this.model.getValueInRange(modelRange, eol);\n };\n ViewModel.prototype.getModelLineMaxColumn = function (modelLineNumber) {\n return this.model.getLineMaxColumn(modelLineNumber);\n };\n ViewModel.prototype.validateModelPosition = function (position) {\n return this.model.validatePosition(position);\n };\n ViewModel.prototype.validateModelRange = function (range) {\n return this.model.validateRange(range);\n };\n ViewModel.prototype.deduceModelPositionRelativeToViewPosition = function (viewAnchorPosition, deltaOffset, lineFeedCnt) {\n var modelAnchor = this.coordinatesConverter.convertViewPositionToModelPosition(viewAnchorPosition);\n if (this.model.getEOL().length === 2) {\n // This model uses CRLF, so the delta must take that into account\n if (deltaOffset < 0) {\n deltaOffset -= lineFeedCnt;\n }\n else {\n deltaOffset += lineFeedCnt;\n }\n }\n var modelAnchorOffset = this.model.getOffsetAt(modelAnchor);\n var resultOffset = modelAnchorOffset + deltaOffset;\n return this.model.getPositionAt(resultOffset);\n };\n ViewModel.prototype.getEOL = function () {\n return this.model.getEOL();\n };\n ViewModel.prototype.getPlainTextToCopy = function (ranges, emptySelectionClipboard, forceCRLF) {\n var _this = this;\n var newLineCharacter = forceCRLF ? '\\r\\n' : this.model.getEOL();\n ranges = ranges.slice(0);\n ranges.sort(Range.compareRangesUsingStarts);\n var nonEmptyRanges = ranges.filter(function (r) { return !r.isEmpty(); });\n if (nonEmptyRanges.length === 0) {\n if (!emptySelectionClipboard) {\n return '';\n }\n var modelLineNumbers = ranges.map(function (r) {\n var viewLineStart = new Position(r.startLineNumber, 1);\n return _this.coordinatesConverter.convertViewPositionToModelPosition(viewLineStart).lineNumber;\n });\n var result_1 = '';\n for (var i = 0; i < modelLineNumbers.length; i++) {\n if (i > 0 && modelLineNumbers[i - 1] === modelLineNumbers[i]) {\n continue;\n }\n result_1 += this.model.getLineContent(modelLineNumbers[i]) + newLineCharacter;\n }\n return result_1;\n }\n var result = [];\n for (var _i = 0, nonEmptyRanges_1 = nonEmptyRanges; _i < nonEmptyRanges_1.length; _i++) {\n var nonEmptyRange = nonEmptyRanges_1[_i];\n result.push(this.getValueInRange(nonEmptyRange, forceCRLF ? 2 /* CRLF */ : 0 /* TextDefined */));\n }\n return result.length === 1 ? result[0] : result;\n };\n ViewModel.prototype.getHTMLToCopy = function (viewRanges, emptySelectionClipboard) {\n if (this.model.getLanguageIdentifier().id === 1 /* PlainText */) {\n return null;\n }\n if (viewRanges.length !== 1) {\n // no multiple selection support at this time\n return null;\n }\n var range = this.coordinatesConverter.convertViewRangeToModelRange(viewRanges[0]);\n if (range.isEmpty()) {\n if (!emptySelectionClipboard) {\n // nothing to copy\n return null;\n }\n var lineNumber = range.startLineNumber;\n range = new Range(lineNumber, this.model.getLineMinColumn(lineNumber), lineNumber, this.model.getLineMaxColumn(lineNumber));\n }\n var fontInfo = this.configuration.editor.fontInfo;\n var colorMap = this._getColorMap();\n return (\"');\n var isBasicASCII = ViewLineRenderingData.isBasicASCII(lineContent, originalModel.mightContainNonBasicASCII());\n var containsRTL = ViewLineRenderingData.containsRTL(lineContent, isBasicASCII, originalModel.mightContainRTL());\n var output = renderViewLine(new RenderLineInput((config.fontInfo.isMonospace && !config.viewInfo.disableMonospaceOptimizations), config.fontInfo.canUseHalfwidthRightwardsArrow, lineContent, false, isBasicASCII, containsRTL, 0, lineTokens, actualDecorations, tabSize, config.fontInfo.spaceWidth, config.viewInfo.stopRenderingLineAfter, config.viewInfo.renderWhitespace, config.viewInfo.renderControlCharacters, config.viewInfo.fontLigatures), sb);\n sb.appendASCIIString('
');\n var absoluteOffsets = output.characterMapping.getAbsoluteOffsets();\n return absoluteOffsets.length > 0 ? absoluteOffsets[absoluteOffsets.length - 1] : 0;\n };\n return InlineViewZonesComputer;\n}(ViewZonesComputer));\nfunction isChangeOrInsert(lineChange) {\n return lineChange.modifiedEndLineNumber > 0;\n}\nfunction isChangeOrDelete(lineChange) {\n return lineChange.originalEndLineNumber > 0;\n}\nfunction createFakeLinesDiv() {\n var r = document.createElement('div');\n r.className = 'diagonal-fill';\n return r;\n}\nregisterThemingParticipant(function (theme, collector) {\n var added = theme.getColor(diffInserted);\n if (added) {\n collector.addRule(\".monaco-editor .line-insert, .monaco-editor .char-insert { background-color: \" + added + \"; }\");\n collector.addRule(\".monaco-diff-editor .line-insert, .monaco-diff-editor .char-insert { background-color: \" + added + \"; }\");\n collector.addRule(\".monaco-editor .inline-added-margin-view-zone { background-color: \" + added + \"; }\");\n }\n var removed = theme.getColor(diffRemoved);\n if (removed) {\n collector.addRule(\".monaco-editor .line-delete, .monaco-editor .char-delete { background-color: \" + removed + \"; }\");\n collector.addRule(\".monaco-diff-editor .line-delete, .monaco-diff-editor .char-delete { background-color: \" + removed + \"; }\");\n collector.addRule(\".monaco-editor .inline-deleted-margin-view-zone { background-color: \" + removed + \"; }\");\n }\n var addedOutline = theme.getColor(diffInsertedOutline);\n if (addedOutline) {\n collector.addRule(\".monaco-editor .line-insert, .monaco-editor .char-insert { border: 1px \" + (theme.type === 'hc' ? 'dashed' : 'solid') + \" \" + addedOutline + \"; }\");\n }\n var removedOutline = theme.getColor(diffRemovedOutline);\n if (removedOutline) {\n collector.addRule(\".monaco-editor .line-delete, .monaco-editor .char-delete { border: 1px \" + (theme.type === 'hc' ? 'dashed' : 'solid') + \" \" + removedOutline + \"; }\");\n }\n var shadow = theme.getColor(scrollbarShadow);\n if (shadow) {\n collector.addRule(\".monaco-diff-editor.side-by-side .editor.modified { box-shadow: -6px 0 5px -5px \" + shadow + \"; }\");\n }\n var border = theme.getColor(diffBorder);\n if (border) {\n collector.addRule(\".monaco-diff-editor.side-by-side .editor.modified { border-left: 1px solid \" + border + \"; }\");\n }\n});\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport { createDecorator } from '../../../platform/instantiation/common/instantiation.js';\nexport var IStandaloneThemeService = createDecorator('themeService');\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport { createDecorator } from '../../instantiation/common/instantiation.js';\nexport var IContextViewService = createDecorator('contextViewService');\nexport var IContextMenuService = createDecorator('contextMenuService');\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport { createDecorator } from '../../instantiation/common/instantiation.js';\nexport var IKeybindingService = createDecorator('keybindingService');\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nvar __param = (this && this.__param) || function (paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n};\nimport * as browser from '../../../base/browser/browser.js';\nimport * as aria from '../../../base/browser/ui/aria/aria.js';\nimport { Disposable, combinedDisposable, toDisposable } from '../../../base/common/lifecycle.js';\nimport { ICodeEditorService } from '../../browser/services/codeEditorService.js';\nimport { CodeEditorWidget } from '../../browser/widget/codeEditorWidget.js';\nimport { DiffEditorWidget } from '../../browser/widget/diffEditorWidget.js';\nimport { InternalEditorAction } from '../../common/editorAction.js';\nimport { IEditorWorkerService } from '../../common/services/editorWorkerService.js';\nimport { StandaloneKeybindingService, applyConfigurationValues } from './simpleServices.js';\nimport { IStandaloneThemeService } from '../common/standaloneThemeService.js';\nimport { MenuRegistry } from '../../../platform/actions/common/actions.js';\nimport { CommandsRegistry, ICommandService } from '../../../platform/commands/common/commands.js';\nimport { IConfigurationService } from '../../../platform/configuration/common/configuration.js';\nimport { ContextKeyExpr, IContextKeyService } from '../../../platform/contextkey/common/contextkey.js';\nimport { IContextViewService } from '../../../platform/contextview/browser/contextView.js';\nimport { IInstantiationService } from '../../../platform/instantiation/common/instantiation.js';\nimport { IKeybindingService } from '../../../platform/keybinding/common/keybinding.js';\nimport { INotificationService } from '../../../platform/notification/common/notification.js';\nimport { IThemeService } from '../../../platform/theme/common/themeService.js';\nimport { IAccessibilityService } from '../../../platform/accessibility/common/accessibility.js';\nimport { StandaloneCodeEditorNLS } from '../../common/standaloneStrings.js';\nvar LAST_GENERATED_COMMAND_ID = 0;\nvar ariaDomNodeCreated = false;\nfunction createAriaDomNode() {\n if (ariaDomNodeCreated) {\n return;\n }\n ariaDomNodeCreated = true;\n aria.setARIAContainer(document.body);\n}\n/**\n * A code editor to be used both by the standalone editor and the standalone diff editor.\n */\nvar StandaloneCodeEditor = /** @class */ (function (_super) {\n __extends(StandaloneCodeEditor, _super);\n function StandaloneCodeEditor(domElement, options, instantiationService, codeEditorService, commandService, contextKeyService, keybindingService, themeService, notificationService, accessibilityService) {\n var _this = this;\n options = options || {};\n options.ariaLabel = options.ariaLabel || StandaloneCodeEditorNLS.editorViewAccessibleLabel;\n options.ariaLabel = options.ariaLabel + ';' + (browser.isIE\n ? StandaloneCodeEditorNLS.accessibilityHelpMessageIE\n : StandaloneCodeEditorNLS.accessibilityHelpMessage);\n _this = _super.call(this, domElement, options, {}, instantiationService, codeEditorService, commandService, contextKeyService, themeService, notificationService, accessibilityService) || this;\n if (keybindingService instanceof StandaloneKeybindingService) {\n _this._standaloneKeybindingService = keybindingService;\n }\n // Create the ARIA dom node as soon as the first editor is instantiated\n createAriaDomNode();\n return _this;\n }\n StandaloneCodeEditor.prototype.addCommand = function (keybinding, handler, context) {\n if (!this._standaloneKeybindingService) {\n console.warn('Cannot add command because the editor is configured with an unrecognized KeybindingService');\n return null;\n }\n var commandId = 'DYNAMIC_' + (++LAST_GENERATED_COMMAND_ID);\n var whenExpression = ContextKeyExpr.deserialize(context);\n this._standaloneKeybindingService.addDynamicKeybinding(commandId, keybinding, handler, whenExpression);\n return commandId;\n };\n StandaloneCodeEditor.prototype.createContextKey = function (key, defaultValue) {\n return this._contextKeyService.createKey(key, defaultValue);\n };\n StandaloneCodeEditor.prototype.addAction = function (_descriptor) {\n var _this = this;\n if ((typeof _descriptor.id !== 'string') || (typeof _descriptor.label !== 'string') || (typeof _descriptor.run !== 'function')) {\n throw new Error('Invalid action descriptor, `id`, `label` and `run` are required properties!');\n }\n if (!this._standaloneKeybindingService) {\n console.warn('Cannot add keybinding because the editor is configured with an unrecognized KeybindingService');\n return Disposable.None;\n }\n // Read descriptor options\n var id = _descriptor.id;\n var label = _descriptor.label;\n var precondition = ContextKeyExpr.and(ContextKeyExpr.equals('editorId', this.getId()), ContextKeyExpr.deserialize(_descriptor.precondition));\n var keybindings = _descriptor.keybindings;\n var keybindingsWhen = ContextKeyExpr.and(precondition, ContextKeyExpr.deserialize(_descriptor.keybindingContext));\n var contextMenuGroupId = _descriptor.contextMenuGroupId || null;\n var contextMenuOrder = _descriptor.contextMenuOrder || 0;\n var run = function () {\n return Promise.resolve(_descriptor.run(_this));\n };\n var toDispose = [];\n // Generate a unique id to allow the same descriptor.id across multiple editor instances\n var uniqueId = this.getId() + ':' + id;\n // Register the command\n toDispose.push(CommandsRegistry.registerCommand(uniqueId, run));\n // Register the context menu item\n if (contextMenuGroupId) {\n var menuItem = {\n command: {\n id: uniqueId,\n title: label\n },\n when: precondition,\n group: contextMenuGroupId,\n order: contextMenuOrder\n };\n toDispose.push(MenuRegistry.appendMenuItem(7 /* EditorContext */, menuItem));\n }\n // Register the keybindings\n if (Array.isArray(keybindings)) {\n toDispose = toDispose.concat(keybindings.map(function (kb) {\n return _this._standaloneKeybindingService.addDynamicKeybinding(uniqueId, kb, run, keybindingsWhen);\n }));\n }\n // Finally, register an internal editor action\n var internalAction = new InternalEditorAction(uniqueId, label, label, precondition, run, this._contextKeyService);\n // Store it under the original id, such that trigger with the original id will work\n this._actions[id] = internalAction;\n toDispose.push(toDisposable(function () {\n delete _this._actions[id];\n }));\n return combinedDisposable(toDispose);\n };\n StandaloneCodeEditor = __decorate([\n __param(2, IInstantiationService),\n __param(3, ICodeEditorService),\n __param(4, ICommandService),\n __param(5, IContextKeyService),\n __param(6, IKeybindingService),\n __param(7, IThemeService),\n __param(8, INotificationService),\n __param(9, IAccessibilityService)\n ], StandaloneCodeEditor);\n return StandaloneCodeEditor;\n}(CodeEditorWidget));\nexport { StandaloneCodeEditor };\nvar StandaloneEditor = /** @class */ (function (_super) {\n __extends(StandaloneEditor, _super);\n function StandaloneEditor(domElement, options, toDispose, instantiationService, codeEditorService, commandService, contextKeyService, keybindingService, contextViewService, themeService, notificationService, configurationService, accessibilityService) {\n var _this = this;\n applyConfigurationValues(configurationService, options, false);\n options = options || {};\n if (typeof options.theme === 'string') {\n themeService.setTheme(options.theme);\n }\n var _model = options.model;\n delete options.model;\n _this = _super.call(this, domElement, options, instantiationService, codeEditorService, commandService, contextKeyService, keybindingService, themeService, notificationService, accessibilityService) || this;\n _this._contextViewService = contextViewService;\n _this._configurationService = configurationService;\n _this._register(toDispose);\n var model;\n if (typeof _model === 'undefined') {\n model = self.monaco.editor.createModel(options.value || '', options.language || 'text/plain');\n _this._ownsModel = true;\n }\n else {\n model = _model;\n _this._ownsModel = false;\n }\n _this._attachModel(model);\n if (model) {\n var e = {\n oldModelUrl: null,\n newModelUrl: model.uri\n };\n _this._onDidChangeModel.fire(e);\n }\n return _this;\n }\n StandaloneEditor.prototype.dispose = function () {\n _super.prototype.dispose.call(this);\n };\n StandaloneEditor.prototype.updateOptions = function (newOptions) {\n applyConfigurationValues(this._configurationService, newOptions, false);\n _super.prototype.updateOptions.call(this, newOptions);\n };\n StandaloneEditor.prototype._attachModel = function (model) {\n _super.prototype._attachModel.call(this, model);\n if (this._modelData) {\n this._contextViewService.setContainer(this._modelData.view.domNode.domNode);\n }\n };\n StandaloneEditor.prototype._postDetachModelCleanup = function (detachedModel) {\n _super.prototype._postDetachModelCleanup.call(this, detachedModel);\n if (detachedModel && this._ownsModel) {\n detachedModel.dispose();\n this._ownsModel = false;\n }\n };\n StandaloneEditor = __decorate([\n __param(3, IInstantiationService),\n __param(4, ICodeEditorService),\n __param(5, ICommandService),\n __param(6, IContextKeyService),\n __param(7, IKeybindingService),\n __param(8, IContextViewService),\n __param(9, IStandaloneThemeService),\n __param(10, INotificationService),\n __param(11, IConfigurationService),\n __param(12, IAccessibilityService)\n ], StandaloneEditor);\n return StandaloneEditor;\n}(StandaloneCodeEditor));\nexport { StandaloneEditor };\nvar StandaloneDiffEditor = /** @class */ (function (_super) {\n __extends(StandaloneDiffEditor, _super);\n function StandaloneDiffEditor(domElement, options, toDispose, instantiationService, contextKeyService, keybindingService, contextViewService, editorWorkerService, codeEditorService, themeService, notificationService, configurationService) {\n var _this = this;\n applyConfigurationValues(configurationService, options, true);\n options = options || {};\n if (typeof options.theme === 'string') {\n options.theme = themeService.setTheme(options.theme);\n }\n _this = _super.call(this, domElement, options, editorWorkerService, contextKeyService, instantiationService, codeEditorService, themeService, notificationService) || this;\n _this._contextViewService = contextViewService;\n _this._configurationService = configurationService;\n _this._register(toDispose);\n _this._contextViewService.setContainer(_this._containerDomElement);\n return _this;\n }\n StandaloneDiffEditor.prototype.dispose = function () {\n _super.prototype.dispose.call(this);\n };\n StandaloneDiffEditor.prototype.updateOptions = function (newOptions) {\n applyConfigurationValues(this._configurationService, newOptions, true);\n _super.prototype.updateOptions.call(this, newOptions);\n };\n StandaloneDiffEditor.prototype._createInnerEditor = function (instantiationService, container, options) {\n return instantiationService.createInstance(StandaloneCodeEditor, container, options);\n };\n StandaloneDiffEditor.prototype.getOriginalEditor = function () {\n return _super.prototype.getOriginalEditor.call(this);\n };\n StandaloneDiffEditor.prototype.getModifiedEditor = function () {\n return _super.prototype.getModifiedEditor.call(this);\n };\n StandaloneDiffEditor.prototype.addCommand = function (keybinding, handler, context) {\n return this.getModifiedEditor().addCommand(keybinding, handler, context);\n };\n StandaloneDiffEditor.prototype.createContextKey = function (key, defaultValue) {\n return this.getModifiedEditor().createContextKey(key, defaultValue);\n };\n StandaloneDiffEditor.prototype.addAction = function (descriptor) {\n return this.getModifiedEditor().addAction(descriptor);\n };\n StandaloneDiffEditor = __decorate([\n __param(3, IInstantiationService),\n __param(4, IContextKeyService),\n __param(5, IKeybindingService),\n __param(6, IContextViewService),\n __param(7, IEditorWorkerService),\n __param(8, ICodeEditorService),\n __param(9, IStandaloneThemeService),\n __param(10, INotificationService),\n __param(11, IConfigurationService)\n ], StandaloneDiffEditor);\n return StandaloneDiffEditor;\n}(DiffEditorWidget));\nexport { StandaloneDiffEditor };\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport { createDecorator } from '../../../platform/instantiation/common/instantiation.js';\nexport var IBulkEditService = createDecorator('IWorkspaceEditService');\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport { createDecorator } from '../../../platform/instantiation/common/instantiation.js';\nexport var IModeService = createDecorator('modeService');\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nvar FrankensteinMode = /** @class */ (function () {\n function FrankensteinMode(languageIdentifier) {\n this._languageIdentifier = languageIdentifier;\n }\n FrankensteinMode.prototype.getId = function () {\n return this._languageIdentifier.language;\n };\n return FrankensteinMode;\n}());\nexport { FrankensteinMode };\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport { basename, posix } from './path.js';\nimport { endsWith, startsWithUTF8BOM } from './strings.js';\nimport { match } from './glob.js';\nexport var MIME_TEXT = 'text/plain';\nexport var MIME_UNKNOWN = 'application/unknown';\nvar registeredAssociations = [];\nvar nonUserRegisteredAssociations = [];\nvar userRegisteredAssociations = [];\n/**\n * Associate a text mime to the registry.\n */\nexport function registerTextMime(association, warnOnOverwrite) {\n if (warnOnOverwrite === void 0) { warnOnOverwrite = false; }\n // Register\n var associationItem = toTextMimeAssociationItem(association);\n registeredAssociations.push(associationItem);\n if (!associationItem.userConfigured) {\n nonUserRegisteredAssociations.push(associationItem);\n }\n else {\n userRegisteredAssociations.push(associationItem);\n }\n // Check for conflicts unless this is a user configured association\n if (warnOnOverwrite && !associationItem.userConfigured) {\n registeredAssociations.forEach(function (a) {\n if (a.mime === associationItem.mime || a.userConfigured) {\n return; // same mime or userConfigured is ok\n }\n if (associationItem.extension && a.extension === associationItem.extension) {\n console.warn(\"Overwriting extension <<\" + associationItem.extension + \">> to now point to mime <<\" + associationItem.mime + \">>\");\n }\n if (associationItem.filename && a.filename === associationItem.filename) {\n console.warn(\"Overwriting filename <<\" + associationItem.filename + \">> to now point to mime <<\" + associationItem.mime + \">>\");\n }\n if (associationItem.filepattern && a.filepattern === associationItem.filepattern) {\n console.warn(\"Overwriting filepattern <<\" + associationItem.filepattern + \">> to now point to mime <<\" + associationItem.mime + \">>\");\n }\n if (associationItem.firstline && a.firstline === associationItem.firstline) {\n console.warn(\"Overwriting firstline <<\" + associationItem.firstline + \">> to now point to mime <<\" + associationItem.mime + \">>\");\n }\n });\n }\n}\nfunction toTextMimeAssociationItem(association) {\n return {\n id: association.id,\n mime: association.mime,\n filename: association.filename,\n extension: association.extension,\n filepattern: association.filepattern,\n firstline: association.firstline,\n userConfigured: association.userConfigured,\n filenameLowercase: association.filename ? association.filename.toLowerCase() : undefined,\n extensionLowercase: association.extension ? association.extension.toLowerCase() : undefined,\n filepatternLowercase: association.filepattern ? association.filepattern.toLowerCase() : undefined,\n filepatternOnPath: association.filepattern ? association.filepattern.indexOf(posix.sep) >= 0 : false\n };\n}\n/**\n * Given a file, return the best matching mime type for it\n */\nexport function guessMimeTypes(path, firstLine) {\n if (!path) {\n return [MIME_UNKNOWN];\n }\n path = path.toLowerCase();\n var filename = basename(path);\n // 1.) User configured mappings have highest priority\n var configuredMime = guessMimeTypeByPath(path, filename, userRegisteredAssociations);\n if (configuredMime) {\n return [configuredMime, MIME_TEXT];\n }\n // 2.) Registered mappings have middle priority\n var registeredMime = guessMimeTypeByPath(path, filename, nonUserRegisteredAssociations);\n if (registeredMime) {\n return [registeredMime, MIME_TEXT];\n }\n // 3.) Firstline has lowest priority\n if (firstLine) {\n var firstlineMime = guessMimeTypeByFirstline(firstLine);\n if (firstlineMime) {\n return [firstlineMime, MIME_TEXT];\n }\n }\n return [MIME_UNKNOWN];\n}\nfunction guessMimeTypeByPath(path, filename, associations) {\n var filenameMatch = null;\n var patternMatch = null;\n var extensionMatch = null;\n // We want to prioritize associations based on the order they are registered so that the last registered\n // association wins over all other. This is for https://github.com/Microsoft/vscode/issues/20074\n for (var i = associations.length - 1; i >= 0; i--) {\n var association = associations[i];\n // First exact name match\n if (filename === association.filenameLowercase) {\n filenameMatch = association;\n break; // take it!\n }\n // Longest pattern match\n if (association.filepattern) {\n if (!patternMatch || association.filepattern.length > patternMatch.filepattern.length) {\n var target = association.filepatternOnPath ? path : filename; // match on full path if pattern contains path separator\n if (match(association.filepatternLowercase, target)) {\n patternMatch = association;\n }\n }\n }\n // Longest extension match\n if (association.extension) {\n if (!extensionMatch || association.extension.length > extensionMatch.extension.length) {\n if (endsWith(filename, association.extensionLowercase)) {\n extensionMatch = association;\n }\n }\n }\n }\n // 1.) Exact name match has second highest prio\n if (filenameMatch) {\n return filenameMatch.mime;\n }\n // 2.) Match on pattern\n if (patternMatch) {\n return patternMatch.mime;\n }\n // 3.) Match on extension comes next\n if (extensionMatch) {\n return extensionMatch.mime;\n }\n return null;\n}\nfunction guessMimeTypeByFirstline(firstLine) {\n if (startsWithUTF8BOM(firstLine)) {\n firstLine = firstLine.substr(1);\n }\n if (firstLine.length > 0) {\n for (var _i = 0, registeredAssociations_1 = registeredAssociations; _i < registeredAssociations_1.length; _i++) {\n var association = registeredAssociations_1[_i];\n if (!association.firstline) {\n continue;\n }\n var matches = firstLine.match(association.firstline);\n if (matches && matches.length > 0) {\n return association.mime;\n }\n }\n }\n return null;\n}\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport * as nls from '../../../nls.js';\nimport { Emitter } from '../../../base/common/event.js';\nimport { LanguageIdentifier } from '../modes.js';\nimport { LanguageConfigurationRegistry } from './languageConfigurationRegistry.js';\nimport { Registry } from '../../../platform/registry/common/platform.js';\n// Define extension point ids\nexport var Extensions = {\n ModesRegistry: 'editor.modesRegistry'\n};\nvar EditorModesRegistry = /** @class */ (function () {\n function EditorModesRegistry() {\n this._onDidChangeLanguages = new Emitter();\n this.onDidChangeLanguages = this._onDidChangeLanguages.event;\n this._languages = [];\n this._dynamicLanguages = [];\n }\n // --- languages\n EditorModesRegistry.prototype.registerLanguage = function (def) {\n this._languages.push(def);\n this._onDidChangeLanguages.fire(undefined);\n };\n EditorModesRegistry.prototype.getLanguages = function () {\n return [].concat(this._languages).concat(this._dynamicLanguages);\n };\n return EditorModesRegistry;\n}());\nexport { EditorModesRegistry };\nexport var ModesRegistry = new EditorModesRegistry();\nRegistry.add(Extensions.ModesRegistry, ModesRegistry);\nexport var PLAINTEXT_MODE_ID = 'plaintext';\nexport var PLAINTEXT_LANGUAGE_IDENTIFIER = new LanguageIdentifier(PLAINTEXT_MODE_ID, 1 /* PlainText */);\nModesRegistry.registerLanguage({\n id: PLAINTEXT_MODE_ID,\n extensions: ['.txt', '.gitignore'],\n aliases: [nls.localize('plainText.alias', \"Plain Text\"), 'text'],\n mimetypes: ['text/plain']\n});\nLanguageConfigurationRegistry.register(PLAINTEXT_LANGUAGE_IDENTIFIER, {\n brackets: [\n ['(', ')'],\n ['[', ']'],\n ['{', '}'],\n ]\n});\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { onUnexpectedError } from '../../../base/common/errors.js';\nimport { Emitter } from '../../../base/common/event.js';\nimport { Disposable } from '../../../base/common/lifecycle.js';\nimport * as mime from '../../../base/common/mime.js';\nimport * as strings from '../../../base/common/strings.js';\nimport { LanguageIdentifier } from '../modes.js';\nimport { ModesRegistry } from '../modes/modesRegistry.js';\nimport { NULL_LANGUAGE_IDENTIFIER, NULL_MODE_ID } from '../modes/nullMode.js';\nimport { Extensions } from '../../../platform/configuration/common/configurationRegistry.js';\nimport { Registry } from '../../../platform/registry/common/platform.js';\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\nvar LanguagesRegistry = /** @class */ (function (_super) {\n __extends(LanguagesRegistry, _super);\n function LanguagesRegistry(useModesRegistry, warnOnOverwrite) {\n if (useModesRegistry === void 0) { useModesRegistry = true; }\n if (warnOnOverwrite === void 0) { warnOnOverwrite = false; }\n var _this = _super.call(this) || this;\n _this._onDidChange = _this._register(new Emitter());\n _this.onDidChange = _this._onDidChange.event;\n _this._warnOnOverwrite = warnOnOverwrite;\n _this._nextLanguageId2 = 1;\n _this._languageIdToLanguage = [];\n _this._languageToLanguageId = Object.create(null);\n _this._languages = {};\n _this._mimeTypesMap = {};\n _this._nameMap = {};\n _this._lowercaseNameMap = {};\n if (useModesRegistry) {\n _this._initializeFromRegistry();\n _this._register(ModesRegistry.onDidChangeLanguages(function (m) { return _this._initializeFromRegistry(); }));\n }\n return _this;\n }\n LanguagesRegistry.prototype._initializeFromRegistry = function () {\n this._languages = {};\n this._mimeTypesMap = {};\n this._nameMap = {};\n this._lowercaseNameMap = {};\n var desc = ModesRegistry.getLanguages();\n this._registerLanguages(desc);\n };\n LanguagesRegistry.prototype._registerLanguages = function (desc) {\n var _this = this;\n for (var _i = 0, desc_1 = desc; _i < desc_1.length; _i++) {\n var d = desc_1[_i];\n this._registerLanguage(d);\n }\n // Rebuild fast path maps\n this._mimeTypesMap = {};\n this._nameMap = {};\n this._lowercaseNameMap = {};\n Object.keys(this._languages).forEach(function (langId) {\n var language = _this._languages[langId];\n if (language.name) {\n _this._nameMap[language.name] = language.identifier;\n }\n language.aliases.forEach(function (alias) {\n _this._lowercaseNameMap[alias.toLowerCase()] = language.identifier;\n });\n language.mimetypes.forEach(function (mimetype) {\n _this._mimeTypesMap[mimetype] = language.identifier;\n });\n });\n Registry.as(Extensions.Configuration).registerOverrideIdentifiers(ModesRegistry.getLanguages().map(function (language) { return language.id; }));\n this._onDidChange.fire();\n };\n LanguagesRegistry.prototype._getLanguageId = function (language) {\n if (this._languageToLanguageId[language]) {\n return this._languageToLanguageId[language];\n }\n var languageId = this._nextLanguageId2++;\n this._languageIdToLanguage[languageId] = language;\n this._languageToLanguageId[language] = languageId;\n return languageId;\n };\n LanguagesRegistry.prototype._registerLanguage = function (lang) {\n var langId = lang.id;\n var resolvedLanguage;\n if (hasOwnProperty.call(this._languages, langId)) {\n resolvedLanguage = this._languages[langId];\n }\n else {\n var languageId = this._getLanguageId(langId);\n resolvedLanguage = {\n identifier: new LanguageIdentifier(langId, languageId),\n name: null,\n mimetypes: [],\n aliases: [],\n extensions: [],\n filenames: [],\n configurationFiles: []\n };\n this._languages[langId] = resolvedLanguage;\n }\n this._mergeLanguage(resolvedLanguage, lang);\n };\n LanguagesRegistry.prototype._mergeLanguage = function (resolvedLanguage, lang) {\n var _a;\n var langId = lang.id;\n var primaryMime = null;\n if (Array.isArray(lang.mimetypes) && lang.mimetypes.length > 0) {\n (_a = resolvedLanguage.mimetypes).push.apply(_a, lang.mimetypes);\n primaryMime = lang.mimetypes[0];\n }\n if (!primaryMime) {\n primaryMime = \"text/x-\" + langId;\n resolvedLanguage.mimetypes.push(primaryMime);\n }\n if (Array.isArray(lang.extensions)) {\n for (var _i = 0, _b = lang.extensions; _i < _b.length; _i++) {\n var extension = _b[_i];\n mime.registerTextMime({ id: langId, mime: primaryMime, extension: extension }, this._warnOnOverwrite);\n resolvedLanguage.extensions.push(extension);\n }\n }\n if (Array.isArray(lang.filenames)) {\n for (var _c = 0, _d = lang.filenames; _c < _d.length; _c++) {\n var filename = _d[_c];\n mime.registerTextMime({ id: langId, mime: primaryMime, filename: filename }, this._warnOnOverwrite);\n resolvedLanguage.filenames.push(filename);\n }\n }\n if (Array.isArray(lang.filenamePatterns)) {\n for (var _e = 0, _f = lang.filenamePatterns; _e < _f.length; _e++) {\n var filenamePattern = _f[_e];\n mime.registerTextMime({ id: langId, mime: primaryMime, filepattern: filenamePattern }, this._warnOnOverwrite);\n }\n }\n if (typeof lang.firstLine === 'string' && lang.firstLine.length > 0) {\n var firstLineRegexStr = lang.firstLine;\n if (firstLineRegexStr.charAt(0) !== '^') {\n firstLineRegexStr = '^' + firstLineRegexStr;\n }\n try {\n var firstLineRegex = new RegExp(firstLineRegexStr);\n if (!strings.regExpLeadsToEndlessLoop(firstLineRegex)) {\n mime.registerTextMime({ id: langId, mime: primaryMime, firstline: firstLineRegex }, this._warnOnOverwrite);\n }\n }\n catch (err) {\n // Most likely, the regex was bad\n onUnexpectedError(err);\n }\n }\n resolvedLanguage.aliases.push(langId);\n var langAliases = null;\n if (typeof lang.aliases !== 'undefined' && Array.isArray(lang.aliases)) {\n if (lang.aliases.length === 0) {\n // signal that this language should not get a name\n langAliases = [null];\n }\n else {\n langAliases = lang.aliases;\n }\n }\n if (langAliases !== null) {\n for (var _g = 0, langAliases_1 = langAliases; _g < langAliases_1.length; _g++) {\n var langAlias = langAliases_1[_g];\n if (!langAlias || langAlias.length === 0) {\n continue;\n }\n resolvedLanguage.aliases.push(langAlias);\n }\n }\n var containsAliases = (langAliases !== null && langAliases.length > 0);\n if (containsAliases && langAliases[0] === null) {\n // signal that this language should not get a name\n }\n else {\n var bestName = (containsAliases ? langAliases[0] : null) || langId;\n if (containsAliases || !resolvedLanguage.name) {\n resolvedLanguage.name = bestName;\n }\n }\n if (lang.configuration) {\n resolvedLanguage.configurationFiles.push(lang.configuration);\n }\n };\n LanguagesRegistry.prototype.isRegisteredMode = function (mimetypeOrModeId) {\n // Is this a known mime type ?\n if (hasOwnProperty.call(this._mimeTypesMap, mimetypeOrModeId)) {\n return true;\n }\n // Is this a known mode id ?\n return hasOwnProperty.call(this._languages, mimetypeOrModeId);\n };\n LanguagesRegistry.prototype.getModeIdForLanguageNameLowercase = function (languageNameLower) {\n if (!hasOwnProperty.call(this._lowercaseNameMap, languageNameLower)) {\n return null;\n }\n return this._lowercaseNameMap[languageNameLower].language;\n };\n LanguagesRegistry.prototype.extractModeIds = function (commaSeparatedMimetypesOrCommaSeparatedIds) {\n var _this = this;\n if (!commaSeparatedMimetypesOrCommaSeparatedIds) {\n return [];\n }\n return (commaSeparatedMimetypesOrCommaSeparatedIds.\n split(',').\n map(function (mimeTypeOrId) { return mimeTypeOrId.trim(); }).\n map(function (mimeTypeOrId) {\n if (hasOwnProperty.call(_this._mimeTypesMap, mimeTypeOrId)) {\n return _this._mimeTypesMap[mimeTypeOrId].language;\n }\n return mimeTypeOrId;\n }).\n filter(function (modeId) {\n return hasOwnProperty.call(_this._languages, modeId);\n }));\n };\n LanguagesRegistry.prototype.getLanguageIdentifier = function (_modeId) {\n if (_modeId === NULL_MODE_ID || _modeId === 0 /* Null */) {\n return NULL_LANGUAGE_IDENTIFIER;\n }\n var modeId;\n if (typeof _modeId === 'string') {\n modeId = _modeId;\n }\n else {\n modeId = this._languageIdToLanguage[_modeId];\n if (!modeId) {\n return null;\n }\n }\n if (!hasOwnProperty.call(this._languages, modeId)) {\n return null;\n }\n return this._languages[modeId].identifier;\n };\n LanguagesRegistry.prototype.getModeIdsFromFilepathOrFirstLine = function (filepath, firstLine) {\n if (!filepath && !firstLine) {\n return [];\n }\n var mimeTypes = mime.guessMimeTypes(filepath, firstLine);\n return this.extractModeIds(mimeTypes.join(','));\n };\n return LanguagesRegistry;\n}(Disposable));\nexport { LanguagesRegistry };\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { Emitter } from '../../../base/common/event.js';\nimport { Disposable } from '../../../base/common/lifecycle.js';\nimport { FrankensteinMode } from '../modes/abstractMode.js';\nimport { NULL_LANGUAGE_IDENTIFIER } from '../modes/nullMode.js';\nimport { LanguagesRegistry } from './languagesRegistry.js';\nvar LanguageSelection = /** @class */ (function (_super) {\n __extends(LanguageSelection, _super);\n function LanguageSelection(onLanguagesMaybeChanged, selector) {\n var _this = _super.call(this) || this;\n _this._onDidChange = _this._register(new Emitter());\n _this.onDidChange = _this._onDidChange.event;\n _this._selector = selector;\n _this.languageIdentifier = _this._selector();\n _this._register(onLanguagesMaybeChanged(function () { return _this._evaluate(); }));\n return _this;\n }\n LanguageSelection.prototype._evaluate = function () {\n var languageIdentifier = this._selector();\n if (languageIdentifier.id === this.languageIdentifier.id) {\n // no change\n return;\n }\n this.languageIdentifier = languageIdentifier;\n this._onDidChange.fire(this.languageIdentifier);\n };\n return LanguageSelection;\n}(Disposable));\nvar ModeServiceImpl = /** @class */ (function () {\n function ModeServiceImpl(warnOnOverwrite) {\n var _this = this;\n if (warnOnOverwrite === void 0) { warnOnOverwrite = false; }\n this._onDidCreateMode = new Emitter();\n this.onDidCreateMode = this._onDidCreateMode.event;\n this._onLanguagesMaybeChanged = new Emitter();\n this.onLanguagesMaybeChanged = this._onLanguagesMaybeChanged.event;\n this._instantiatedModes = {};\n this._registry = new LanguagesRegistry(true, warnOnOverwrite);\n this._registry.onDidChange(function () { return _this._onLanguagesMaybeChanged.fire(); });\n }\n ModeServiceImpl.prototype.isRegisteredMode = function (mimetypeOrModeId) {\n return this._registry.isRegisteredMode(mimetypeOrModeId);\n };\n ModeServiceImpl.prototype.getModeIdForLanguageName = function (alias) {\n return this._registry.getModeIdForLanguageNameLowercase(alias);\n };\n ModeServiceImpl.prototype.getModeIdByFilepathOrFirstLine = function (filepath, firstLine) {\n var modeIds = this._registry.getModeIdsFromFilepathOrFirstLine(filepath, firstLine);\n if (modeIds.length > 0) {\n return modeIds[0];\n }\n return null;\n };\n ModeServiceImpl.prototype.getModeId = function (commaSeparatedMimetypesOrCommaSeparatedIds) {\n var modeIds = this._registry.extractModeIds(commaSeparatedMimetypesOrCommaSeparatedIds);\n if (modeIds.length > 0) {\n return modeIds[0];\n }\n return null;\n };\n ModeServiceImpl.prototype.getLanguageIdentifier = function (modeId) {\n return this._registry.getLanguageIdentifier(modeId);\n };\n // --- instantiation\n ModeServiceImpl.prototype.create = function (commaSeparatedMimetypesOrCommaSeparatedIds) {\n var _this = this;\n return new LanguageSelection(this.onLanguagesMaybeChanged, function () {\n var modeId = _this.getModeId(commaSeparatedMimetypesOrCommaSeparatedIds);\n return _this._createModeAndGetLanguageIdentifier(modeId);\n });\n };\n ModeServiceImpl.prototype.createByFilepathOrFirstLine = function (filepath, firstLine) {\n var _this = this;\n return new LanguageSelection(this.onLanguagesMaybeChanged, function () {\n var modeId = _this.getModeIdByFilepathOrFirstLine(filepath, firstLine);\n return _this._createModeAndGetLanguageIdentifier(modeId);\n });\n };\n ModeServiceImpl.prototype._createModeAndGetLanguageIdentifier = function (modeId) {\n // Fall back to plain text if no mode was found\n var languageIdentifier = this.getLanguageIdentifier(modeId || 'plaintext') || NULL_LANGUAGE_IDENTIFIER;\n this._getOrCreateMode(languageIdentifier.language);\n return languageIdentifier;\n };\n ModeServiceImpl.prototype.triggerMode = function (commaSeparatedMimetypesOrCommaSeparatedIds) {\n var modeId = this.getModeId(commaSeparatedMimetypesOrCommaSeparatedIds);\n // Fall back to plain text if no mode was found\n this._getOrCreateMode(modeId || 'plaintext');\n };\n ModeServiceImpl.prototype._getOrCreateMode = function (modeId) {\n if (!this._instantiatedModes.hasOwnProperty(modeId)) {\n var languageIdentifier = this.getLanguageIdentifier(modeId) || NULL_LANGUAGE_IDENTIFIER;\n this._instantiatedModes[modeId] = new FrankensteinMode(languageIdentifier);\n this._onDidCreateMode.fire(this._instantiatedModes[modeId]);\n }\n return this._instantiatedModes[modeId];\n };\n return ModeServiceImpl;\n}());\nexport { ModeServiceImpl };\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nvar __param = (this && this.__param) || function (paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n};\nimport { Emitter } from '../../../base/common/event.js';\nimport { Disposable, dispose } from '../../../base/common/lifecycle.js';\nimport * as platform from '../../../base/common/platform.js';\nimport { EDITOR_MODEL_DEFAULTS } from '../config/editorOptions.js';\nimport { TextModel } from '../model/textModel.js';\nimport { PLAINTEXT_LANGUAGE_IDENTIFIER } from '../modes/modesRegistry.js';\nimport { ITextResourcePropertiesService } from './resourceConfiguration.js';\nimport { IConfigurationService } from '../../../platform/configuration/common/configuration.js';\nfunction MODEL_ID(resource) {\n return resource.toString();\n}\nvar ModelData = /** @class */ (function () {\n function ModelData(model, onWillDispose, onDidChangeLanguage) {\n this.model = model;\n this._languageSelection = null;\n this._languageSelectionListener = null;\n this._modelEventListeners = [];\n this._modelEventListeners.push(model.onWillDispose(function () { return onWillDispose(model); }));\n this._modelEventListeners.push(model.onDidChangeLanguage(function (e) { return onDidChangeLanguage(model, e); }));\n }\n ModelData.prototype._disposeLanguageSelection = function () {\n if (this._languageSelectionListener) {\n this._languageSelectionListener.dispose();\n this._languageSelectionListener = null;\n }\n if (this._languageSelection) {\n this._languageSelection.dispose();\n this._languageSelection = null;\n }\n };\n ModelData.prototype.dispose = function () {\n this._modelEventListeners = dispose(this._modelEventListeners);\n this._disposeLanguageSelection();\n };\n ModelData.prototype.setLanguage = function (languageSelection) {\n var _this = this;\n this._disposeLanguageSelection();\n this._languageSelection = languageSelection;\n this._languageSelectionListener = this._languageSelection.onDidChange(function () { return _this.model.setMode(languageSelection.languageIdentifier); });\n this.model.setMode(languageSelection.languageIdentifier);\n };\n return ModelData;\n}());\nvar DEFAULT_EOL = (platform.isLinux || platform.isMacintosh) ? 1 /* LF */ : 2 /* CRLF */;\nvar ModelServiceImpl = /** @class */ (function (_super) {\n __extends(ModelServiceImpl, _super);\n function ModelServiceImpl(configurationService, resourcePropertiesService) {\n var _this = _super.call(this) || this;\n _this._onModelAdded = _this._register(new Emitter());\n _this.onModelAdded = _this._onModelAdded.event;\n _this._onModelRemoved = _this._register(new Emitter());\n _this.onModelRemoved = _this._onModelRemoved.event;\n _this._onModelModeChanged = _this._register(new Emitter());\n _this.onModelModeChanged = _this._onModelModeChanged.event;\n _this._configurationService = configurationService;\n _this._resourcePropertiesService = resourcePropertiesService;\n _this._models = {};\n _this._modelCreationOptionsByLanguageAndResource = Object.create(null);\n _this._configurationServiceSubscription = _this._configurationService.onDidChangeConfiguration(function (e) { return _this._updateModelOptions(); });\n _this._updateModelOptions();\n return _this;\n }\n ModelServiceImpl._readModelOptions = function (config, isForSimpleWidget) {\n var tabSize = EDITOR_MODEL_DEFAULTS.tabSize;\n if (config.editor && typeof config.editor.tabSize !== 'undefined') {\n var parsedTabSize = parseInt(config.editor.tabSize, 10);\n if (!isNaN(parsedTabSize)) {\n tabSize = parsedTabSize;\n }\n if (tabSize < 1) {\n tabSize = 1;\n }\n }\n var indentSize = tabSize;\n if (config.editor && typeof config.editor.indentSize !== 'undefined' && config.editor.indentSize !== 'tabSize') {\n var parsedIndentSize = parseInt(config.editor.indentSize, 10);\n if (!isNaN(parsedIndentSize)) {\n indentSize = parsedIndentSize;\n }\n if (indentSize < 1) {\n indentSize = 1;\n }\n }\n var insertSpaces = EDITOR_MODEL_DEFAULTS.insertSpaces;\n if (config.editor && typeof config.editor.insertSpaces !== 'undefined') {\n insertSpaces = (config.editor.insertSpaces === 'false' ? false : Boolean(config.editor.insertSpaces));\n }\n var newDefaultEOL = DEFAULT_EOL;\n var eol = config.eol;\n if (eol === '\\r\\n') {\n newDefaultEOL = 2 /* CRLF */;\n }\n else if (eol === '\\n') {\n newDefaultEOL = 1 /* LF */;\n }\n var trimAutoWhitespace = EDITOR_MODEL_DEFAULTS.trimAutoWhitespace;\n if (config.editor && typeof config.editor.trimAutoWhitespace !== 'undefined') {\n trimAutoWhitespace = (config.editor.trimAutoWhitespace === 'false' ? false : Boolean(config.editor.trimAutoWhitespace));\n }\n var detectIndentation = EDITOR_MODEL_DEFAULTS.detectIndentation;\n if (config.editor && typeof config.editor.detectIndentation !== 'undefined') {\n detectIndentation = (config.editor.detectIndentation === 'false' ? false : Boolean(config.editor.detectIndentation));\n }\n var largeFileOptimizations = EDITOR_MODEL_DEFAULTS.largeFileOptimizations;\n if (config.editor && typeof config.editor.largeFileOptimizations !== 'undefined') {\n largeFileOptimizations = (config.editor.largeFileOptimizations === 'false' ? false : Boolean(config.editor.largeFileOptimizations));\n }\n return {\n isForSimpleWidget: isForSimpleWidget,\n tabSize: tabSize,\n indentSize: indentSize,\n insertSpaces: insertSpaces,\n detectIndentation: detectIndentation,\n defaultEOL: newDefaultEOL,\n trimAutoWhitespace: trimAutoWhitespace,\n largeFileOptimizations: largeFileOptimizations\n };\n };\n ModelServiceImpl.prototype.getCreationOptions = function (language, resource, isForSimpleWidget) {\n var creationOptions = this._modelCreationOptionsByLanguageAndResource[language + resource];\n if (!creationOptions) {\n var editor = this._configurationService.getValue('editor', { overrideIdentifier: language, resource: resource });\n var eol = this._resourcePropertiesService.getEOL(resource, language);\n creationOptions = ModelServiceImpl._readModelOptions({ editor: editor, eol: eol }, isForSimpleWidget);\n this._modelCreationOptionsByLanguageAndResource[language + resource] = creationOptions;\n }\n return creationOptions;\n };\n ModelServiceImpl.prototype._updateModelOptions = function () {\n var oldOptionsByLanguageAndResource = this._modelCreationOptionsByLanguageAndResource;\n this._modelCreationOptionsByLanguageAndResource = Object.create(null);\n // Update options on all models\n var keys = Object.keys(this._models);\n for (var i = 0, len = keys.length; i < len; i++) {\n var modelId = keys[i];\n var modelData = this._models[modelId];\n var language = modelData.model.getLanguageIdentifier().language;\n var uri = modelData.model.uri;\n var oldOptions = oldOptionsByLanguageAndResource[language + uri];\n var newOptions = this.getCreationOptions(language, uri, modelData.model.isForSimpleWidget);\n ModelServiceImpl._setModelOptionsForModel(modelData.model, newOptions, oldOptions);\n }\n };\n ModelServiceImpl._setModelOptionsForModel = function (model, newOptions, currentOptions) {\n if (currentOptions\n && (currentOptions.detectIndentation === newOptions.detectIndentation)\n && (currentOptions.insertSpaces === newOptions.insertSpaces)\n && (currentOptions.tabSize === newOptions.tabSize)\n && (currentOptions.indentSize === newOptions.indentSize)\n && (currentOptions.trimAutoWhitespace === newOptions.trimAutoWhitespace)) {\n // Same indent opts, no need to touch the model\n return;\n }\n if (newOptions.detectIndentation) {\n model.detectIndentation(newOptions.insertSpaces, newOptions.tabSize);\n model.updateOptions({\n trimAutoWhitespace: newOptions.trimAutoWhitespace\n });\n }\n else {\n model.updateOptions({\n insertSpaces: newOptions.insertSpaces,\n tabSize: newOptions.tabSize,\n indentSize: newOptions.indentSize,\n trimAutoWhitespace: newOptions.trimAutoWhitespace\n });\n }\n };\n ModelServiceImpl.prototype.dispose = function () {\n this._configurationServiceSubscription.dispose();\n _super.prototype.dispose.call(this);\n };\n // --- begin IModelService\n ModelServiceImpl.prototype._createModelData = function (value, languageIdentifier, resource, isForSimpleWidget) {\n var _this = this;\n // create & save the model\n var options = this.getCreationOptions(languageIdentifier.language, resource, isForSimpleWidget);\n var model = new TextModel(value, options, languageIdentifier, resource);\n var modelId = MODEL_ID(model.uri);\n if (this._models[modelId]) {\n // There already exists a model with this id => this is a programmer error\n throw new Error('ModelService: Cannot add model because it already exists!');\n }\n var modelData = new ModelData(model, function (model) { return _this._onWillDispose(model); }, function (model, e) { return _this._onDidChangeLanguage(model, e); });\n this._models[modelId] = modelData;\n return modelData;\n };\n ModelServiceImpl.prototype.createModel = function (value, languageSelection, resource, isForSimpleWidget) {\n if (isForSimpleWidget === void 0) { isForSimpleWidget = false; }\n var modelData;\n if (languageSelection) {\n modelData = this._createModelData(value, languageSelection.languageIdentifier, resource, isForSimpleWidget);\n this.setMode(modelData.model, languageSelection);\n }\n else {\n modelData = this._createModelData(value, PLAINTEXT_LANGUAGE_IDENTIFIER, resource, isForSimpleWidget);\n }\n this._onModelAdded.fire(modelData.model);\n return modelData.model;\n };\n ModelServiceImpl.prototype.setMode = function (model, languageSelection) {\n if (!languageSelection) {\n return;\n }\n var modelData = this._models[MODEL_ID(model.uri)];\n if (!modelData) {\n return;\n }\n modelData.setLanguage(languageSelection);\n };\n ModelServiceImpl.prototype.getModels = function () {\n var ret = [];\n var keys = Object.keys(this._models);\n for (var i = 0, len = keys.length; i < len; i++) {\n var modelId = keys[i];\n ret.push(this._models[modelId].model);\n }\n return ret;\n };\n ModelServiceImpl.prototype.getModel = function (resource) {\n var modelId = MODEL_ID(resource);\n var modelData = this._models[modelId];\n if (!modelData) {\n return null;\n }\n return modelData.model;\n };\n // --- end IModelService\n ModelServiceImpl.prototype._onWillDispose = function (model) {\n var modelId = MODEL_ID(model.uri);\n var modelData = this._models[modelId];\n delete this._models[modelId];\n modelData.dispose();\n // clean up cache\n delete this._modelCreationOptionsByLanguageAndResource[model.getLanguageIdentifier().language + model.uri];\n this._onModelRemoved.fire(model);\n };\n ModelServiceImpl.prototype._onDidChangeLanguage = function (model, e) {\n var oldModeId = e.oldLanguage;\n var newModeId = model.getLanguageIdentifier().language;\n var oldOptions = this.getCreationOptions(oldModeId, model.uri, model.isForSimpleWidget);\n var newOptions = this.getCreationOptions(newModeId, model.uri, model.isForSimpleWidget);\n ModelServiceImpl._setModelOptionsForModel(model, newOptions, oldOptions);\n this._onModelModeChanged.fire({ model: model, oldModeId: oldModeId });\n };\n ModelServiceImpl = __decorate([\n __param(0, IConfigurationService),\n __param(1, ITextResourcePropertiesService)\n ], ModelServiceImpl);\n return ModelServiceImpl;\n}(Disposable));\nexport { ModelServiceImpl };\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { Emitter } from '../../../base/common/event.js';\nimport { Disposable } from '../../../base/common/lifecycle.js';\nvar AbstractCodeEditorService = /** @class */ (function (_super) {\n __extends(AbstractCodeEditorService, _super);\n function AbstractCodeEditorService() {\n var _this = _super.call(this) || this;\n _this._onCodeEditorAdd = _this._register(new Emitter());\n _this.onCodeEditorAdd = _this._onCodeEditorAdd.event;\n _this._onCodeEditorRemove = _this._register(new Emitter());\n _this._onDiffEditorAdd = _this._register(new Emitter());\n _this._onDiffEditorRemove = _this._register(new Emitter());\n _this._codeEditors = Object.create(null);\n _this._diffEditors = Object.create(null);\n return _this;\n }\n AbstractCodeEditorService.prototype.addCodeEditor = function (editor) {\n this._codeEditors[editor.getId()] = editor;\n this._onCodeEditorAdd.fire(editor);\n };\n AbstractCodeEditorService.prototype.removeCodeEditor = function (editor) {\n if (delete this._codeEditors[editor.getId()]) {\n this._onCodeEditorRemove.fire(editor);\n }\n };\n AbstractCodeEditorService.prototype.listCodeEditors = function () {\n var _this = this;\n return Object.keys(this._codeEditors).map(function (id) { return _this._codeEditors[id]; });\n };\n AbstractCodeEditorService.prototype.addDiffEditor = function (editor) {\n this._diffEditors[editor.getId()] = editor;\n this._onDiffEditorAdd.fire(editor);\n };\n AbstractCodeEditorService.prototype.removeDiffEditor = function (editor) {\n if (delete this._diffEditors[editor.getId()]) {\n this._onDiffEditorRemove.fire(editor);\n }\n };\n AbstractCodeEditorService.prototype.listDiffEditors = function () {\n var _this = this;\n return Object.keys(this._diffEditors).map(function (id) { return _this._diffEditors[id]; });\n };\n AbstractCodeEditorService.prototype.getFocusedCodeEditor = function () {\n var editorWithWidgetFocus = null;\n var editors = this.listCodeEditors();\n for (var _i = 0, editors_1 = editors; _i < editors_1.length; _i++) {\n var editor = editors_1[_i];\n if (editor.hasTextFocus()) {\n // bingo!\n return editor;\n }\n if (editor.hasWidgetFocus()) {\n editorWithWidgetFocus = editor;\n }\n }\n return editorWithWidgetFocus;\n };\n return AbstractCodeEditorService;\n}(Disposable));\nexport { AbstractCodeEditorService };\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nvar __param = (this && this.__param) || function (paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n};\nimport * as dom from '../../../base/browser/dom.js';\nimport { dispose as disposeAll } from '../../../base/common/lifecycle.js';\nimport * as strings from '../../../base/common/strings.js';\nimport { URI } from '../../../base/common/uri.js';\nimport { AbstractCodeEditorService } from './abstractCodeEditorService.js';\nimport { isThemeColor } from '../../common/editorCommon.js';\nimport { OverviewRulerLane } from '../../common/model.js';\nimport { IThemeService } from '../../../platform/theme/common/themeService.js';\nvar CodeEditorServiceImpl = /** @class */ (function (_super) {\n __extends(CodeEditorServiceImpl, _super);\n function CodeEditorServiceImpl(themeService, styleSheet) {\n if (styleSheet === void 0) { styleSheet = dom.createStyleSheet(); }\n var _this = _super.call(this) || this;\n _this._styleSheet = styleSheet;\n _this._decorationOptionProviders = Object.create(null);\n _this._themeService = themeService;\n return _this;\n }\n CodeEditorServiceImpl.prototype.registerDecorationType = function (key, options, parentTypeKey) {\n var provider = this._decorationOptionProviders[key];\n if (!provider) {\n var providerArgs = {\n styleSheet: this._styleSheet,\n key: key,\n parentTypeKey: parentTypeKey,\n options: options || Object.create(null)\n };\n if (!parentTypeKey) {\n provider = new DecorationTypeOptionsProvider(this._themeService, providerArgs);\n }\n else {\n provider = new DecorationSubTypeOptionsProvider(this._themeService, providerArgs);\n }\n this._decorationOptionProviders[key] = provider;\n }\n provider.refCount++;\n };\n CodeEditorServiceImpl.prototype.removeDecorationType = function (key) {\n var provider = this._decorationOptionProviders[key];\n if (provider) {\n provider.refCount--;\n if (provider.refCount <= 0) {\n delete this._decorationOptionProviders[key];\n provider.dispose();\n this.listCodeEditors().forEach(function (ed) { return ed.removeDecorations(key); });\n }\n }\n };\n CodeEditorServiceImpl.prototype.resolveDecorationOptions = function (decorationTypeKey, writable) {\n var provider = this._decorationOptionProviders[decorationTypeKey];\n if (!provider) {\n throw new Error('Unknown decoration type key: ' + decorationTypeKey);\n }\n return provider.getOptions(this, writable);\n };\n CodeEditorServiceImpl = __decorate([\n __param(0, IThemeService)\n ], CodeEditorServiceImpl);\n return CodeEditorServiceImpl;\n}(AbstractCodeEditorService));\nexport { CodeEditorServiceImpl };\nvar DecorationSubTypeOptionsProvider = /** @class */ (function () {\n function DecorationSubTypeOptionsProvider(themeService, providerArgs) {\n this._parentTypeKey = providerArgs.parentTypeKey;\n this.refCount = 0;\n this._beforeContentRules = new DecorationCSSRules(3 /* BeforeContentClassName */, providerArgs, themeService);\n this._afterContentRules = new DecorationCSSRules(4 /* AfterContentClassName */, providerArgs, themeService);\n }\n DecorationSubTypeOptionsProvider.prototype.getOptions = function (codeEditorService, writable) {\n var options = codeEditorService.resolveDecorationOptions(this._parentTypeKey, true);\n if (this._beforeContentRules) {\n options.beforeContentClassName = this._beforeContentRules.className;\n }\n if (this._afterContentRules) {\n options.afterContentClassName = this._afterContentRules.className;\n }\n return options;\n };\n DecorationSubTypeOptionsProvider.prototype.dispose = function () {\n if (this._beforeContentRules) {\n this._beforeContentRules.dispose();\n this._beforeContentRules = null;\n }\n if (this._afterContentRules) {\n this._afterContentRules.dispose();\n this._afterContentRules = null;\n }\n };\n return DecorationSubTypeOptionsProvider;\n}());\nvar DecorationTypeOptionsProvider = /** @class */ (function () {\n function DecorationTypeOptionsProvider(themeService, providerArgs) {\n var _this = this;\n this.refCount = 0;\n this._disposables = [];\n var createCSSRules = function (type) {\n var rules = new DecorationCSSRules(type, providerArgs, themeService);\n _this._disposables.push(rules);\n if (rules.hasContent) {\n return rules.className;\n }\n return undefined;\n };\n var createInlineCSSRules = function (type) {\n var rules = new DecorationCSSRules(type, providerArgs, themeService);\n _this._disposables.push(rules);\n if (rules.hasContent) {\n return { className: rules.className, hasLetterSpacing: rules.hasLetterSpacing };\n }\n return null;\n };\n this.className = createCSSRules(0 /* ClassName */);\n var inlineData = createInlineCSSRules(1 /* InlineClassName */);\n if (inlineData) {\n this.inlineClassName = inlineData.className;\n this.inlineClassNameAffectsLetterSpacing = inlineData.hasLetterSpacing;\n }\n this.beforeContentClassName = createCSSRules(3 /* BeforeContentClassName */);\n this.afterContentClassName = createCSSRules(4 /* AfterContentClassName */);\n this.glyphMarginClassName = createCSSRules(2 /* GlyphMarginClassName */);\n var options = providerArgs.options;\n this.isWholeLine = Boolean(options.isWholeLine);\n this.stickiness = options.rangeBehavior;\n var lightOverviewRulerColor = options.light && options.light.overviewRulerColor || options.overviewRulerColor;\n var darkOverviewRulerColor = options.dark && options.dark.overviewRulerColor || options.overviewRulerColor;\n if (typeof lightOverviewRulerColor !== 'undefined'\n || typeof darkOverviewRulerColor !== 'undefined') {\n this.overviewRuler = {\n color: lightOverviewRulerColor || darkOverviewRulerColor,\n darkColor: darkOverviewRulerColor || lightOverviewRulerColor,\n position: options.overviewRulerLane || OverviewRulerLane.Center\n };\n }\n }\n DecorationTypeOptionsProvider.prototype.getOptions = function (codeEditorService, writable) {\n if (!writable) {\n return this;\n }\n return {\n inlineClassName: this.inlineClassName,\n beforeContentClassName: this.beforeContentClassName,\n afterContentClassName: this.afterContentClassName,\n className: this.className,\n glyphMarginClassName: this.glyphMarginClassName,\n isWholeLine: this.isWholeLine,\n overviewRuler: this.overviewRuler,\n stickiness: this.stickiness\n };\n };\n DecorationTypeOptionsProvider.prototype.dispose = function () {\n this._disposables = disposeAll(this._disposables);\n };\n return DecorationTypeOptionsProvider;\n}());\nvar _CSS_MAP = {\n color: 'color:{0} !important;',\n opacity: 'opacity:{0};',\n backgroundColor: 'background-color:{0};',\n outline: 'outline:{0};',\n outlineColor: 'outline-color:{0};',\n outlineStyle: 'outline-style:{0};',\n outlineWidth: 'outline-width:{0};',\n border: 'border:{0};',\n borderColor: 'border-color:{0};',\n borderRadius: 'border-radius:{0};',\n borderSpacing: 'border-spacing:{0};',\n borderStyle: 'border-style:{0};',\n borderWidth: 'border-width:{0};',\n fontStyle: 'font-style:{0};',\n fontWeight: 'font-weight:{0};',\n textDecoration: 'text-decoration:{0};',\n cursor: 'cursor:{0};',\n letterSpacing: 'letter-spacing:{0};',\n gutterIconPath: 'background:url(\\'{0}\\') center center no-repeat;',\n gutterIconSize: 'background-size:{0};',\n contentText: 'content:\\'{0}\\';',\n contentIconPath: 'content:url(\\'{0}\\');',\n margin: 'margin:{0};',\n width: 'width:{0};',\n height: 'height:{0};'\n};\nvar DecorationCSSRules = /** @class */ (function () {\n function DecorationCSSRules(ruleType, providerArgs, themeService) {\n var _this = this;\n this._theme = themeService.getTheme();\n this._ruleType = ruleType;\n this._providerArgs = providerArgs;\n this._usesThemeColors = false;\n this._hasContent = false;\n this._hasLetterSpacing = false;\n var className = CSSNameHelper.getClassName(this._providerArgs.key, ruleType);\n if (this._providerArgs.parentTypeKey) {\n className = className + ' ' + CSSNameHelper.getClassName(this._providerArgs.parentTypeKey, ruleType);\n }\n this._className = className;\n this._unThemedSelector = CSSNameHelper.getSelector(this._providerArgs.key, this._providerArgs.parentTypeKey, ruleType);\n this._buildCSS();\n if (this._usesThemeColors) {\n this._themeListener = themeService.onThemeChange(function (theme) {\n _this._theme = themeService.getTheme();\n _this._removeCSS();\n _this._buildCSS();\n });\n }\n else {\n this._themeListener = null;\n }\n }\n DecorationCSSRules.prototype.dispose = function () {\n if (this._hasContent) {\n this._removeCSS();\n this._hasContent = false;\n }\n if (this._themeListener) {\n this._themeListener.dispose();\n this._themeListener = null;\n }\n };\n Object.defineProperty(DecorationCSSRules.prototype, \"hasContent\", {\n get: function () {\n return this._hasContent;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DecorationCSSRules.prototype, \"hasLetterSpacing\", {\n get: function () {\n return this._hasLetterSpacing;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DecorationCSSRules.prototype, \"className\", {\n get: function () {\n return this._className;\n },\n enumerable: true,\n configurable: true\n });\n DecorationCSSRules.prototype._buildCSS = function () {\n var options = this._providerArgs.options;\n var unthemedCSS, lightCSS, darkCSS;\n switch (this._ruleType) {\n case 0 /* ClassName */:\n unthemedCSS = this.getCSSTextForModelDecorationClassName(options);\n lightCSS = this.getCSSTextForModelDecorationClassName(options.light);\n darkCSS = this.getCSSTextForModelDecorationClassName(options.dark);\n break;\n case 1 /* InlineClassName */:\n unthemedCSS = this.getCSSTextForModelDecorationInlineClassName(options);\n lightCSS = this.getCSSTextForModelDecorationInlineClassName(options.light);\n darkCSS = this.getCSSTextForModelDecorationInlineClassName(options.dark);\n break;\n case 2 /* GlyphMarginClassName */:\n unthemedCSS = this.getCSSTextForModelDecorationGlyphMarginClassName(options);\n lightCSS = this.getCSSTextForModelDecorationGlyphMarginClassName(options.light);\n darkCSS = this.getCSSTextForModelDecorationGlyphMarginClassName(options.dark);\n break;\n case 3 /* BeforeContentClassName */:\n unthemedCSS = this.getCSSTextForModelDecorationContentClassName(options.before);\n lightCSS = this.getCSSTextForModelDecorationContentClassName(options.light && options.light.before);\n darkCSS = this.getCSSTextForModelDecorationContentClassName(options.dark && options.dark.before);\n break;\n case 4 /* AfterContentClassName */:\n unthemedCSS = this.getCSSTextForModelDecorationContentClassName(options.after);\n lightCSS = this.getCSSTextForModelDecorationContentClassName(options.light && options.light.after);\n darkCSS = this.getCSSTextForModelDecorationContentClassName(options.dark && options.dark.after);\n break;\n default:\n throw new Error('Unknown rule type: ' + this._ruleType);\n }\n var sheet = this._providerArgs.styleSheet.sheet;\n var hasContent = false;\n if (unthemedCSS.length > 0) {\n sheet.insertRule(this._unThemedSelector + \" {\" + unthemedCSS + \"}\", 0);\n hasContent = true;\n }\n if (lightCSS.length > 0) {\n sheet.insertRule(\".vs\" + this._unThemedSelector + \" {\" + lightCSS + \"}\", 0);\n hasContent = true;\n }\n if (darkCSS.length > 0) {\n sheet.insertRule(\".vs-dark\" + this._unThemedSelector + \", .hc-black\" + this._unThemedSelector + \" {\" + darkCSS + \"}\", 0);\n hasContent = true;\n }\n this._hasContent = hasContent;\n };\n DecorationCSSRules.prototype._removeCSS = function () {\n dom.removeCSSRulesContainingSelector(this._unThemedSelector, this._providerArgs.styleSheet);\n };\n /**\n * Build the CSS for decorations styled via `className`.\n */\n DecorationCSSRules.prototype.getCSSTextForModelDecorationClassName = function (opts) {\n if (!opts) {\n return '';\n }\n var cssTextArr = [];\n this.collectCSSText(opts, ['backgroundColor'], cssTextArr);\n this.collectCSSText(opts, ['outline', 'outlineColor', 'outlineStyle', 'outlineWidth'], cssTextArr);\n this.collectBorderSettingsCSSText(opts, cssTextArr);\n return cssTextArr.join('');\n };\n /**\n * Build the CSS for decorations styled via `inlineClassName`.\n */\n DecorationCSSRules.prototype.getCSSTextForModelDecorationInlineClassName = function (opts) {\n if (!opts) {\n return '';\n }\n var cssTextArr = [];\n this.collectCSSText(opts, ['fontStyle', 'fontWeight', 'textDecoration', 'cursor', 'color', 'opacity', 'letterSpacing'], cssTextArr);\n if (opts.letterSpacing) {\n this._hasLetterSpacing = true;\n }\n return cssTextArr.join('');\n };\n /**\n * Build the CSS for decorations styled before or after content.\n */\n DecorationCSSRules.prototype.getCSSTextForModelDecorationContentClassName = function (opts) {\n if (!opts) {\n return '';\n }\n var cssTextArr = [];\n if (typeof opts !== 'undefined') {\n this.collectBorderSettingsCSSText(opts, cssTextArr);\n if (typeof opts.contentIconPath !== 'undefined') {\n cssTextArr.push(strings.format(_CSS_MAP.contentIconPath, URI.revive(opts.contentIconPath).toString(true).replace(/'/g, '%27')));\n }\n if (typeof opts.contentText === 'string') {\n var truncated = opts.contentText.match(/^.*$/m)[0]; // only take first line\n var escaped = truncated.replace(/['\\\\]/g, '\\\\$&');\n cssTextArr.push(strings.format(_CSS_MAP.contentText, escaped));\n }\n this.collectCSSText(opts, ['fontStyle', 'fontWeight', 'textDecoration', 'color', 'opacity', 'backgroundColor', 'margin'], cssTextArr);\n if (this.collectCSSText(opts, ['width', 'height'], cssTextArr)) {\n cssTextArr.push('display:inline-block;');\n }\n }\n return cssTextArr.join('');\n };\n /**\n * Build the CSS for decorations styled via `glpyhMarginClassName`.\n */\n DecorationCSSRules.prototype.getCSSTextForModelDecorationGlyphMarginClassName = function (opts) {\n if (!opts) {\n return '';\n }\n var cssTextArr = [];\n if (typeof opts.gutterIconPath !== 'undefined') {\n cssTextArr.push(strings.format(_CSS_MAP.gutterIconPath, URI.revive(opts.gutterIconPath).toString(true).replace(/'/g, '%27')));\n if (typeof opts.gutterIconSize !== 'undefined') {\n cssTextArr.push(strings.format(_CSS_MAP.gutterIconSize, opts.gutterIconSize));\n }\n }\n return cssTextArr.join('');\n };\n DecorationCSSRules.prototype.collectBorderSettingsCSSText = function (opts, cssTextArr) {\n if (this.collectCSSText(opts, ['border', 'borderColor', 'borderRadius', 'borderSpacing', 'borderStyle', 'borderWidth'], cssTextArr)) {\n cssTextArr.push(strings.format('box-sizing: border-box;'));\n return true;\n }\n return false;\n };\n DecorationCSSRules.prototype.collectCSSText = function (opts, properties, cssTextArr) {\n var lenBefore = cssTextArr.length;\n for (var _i = 0, properties_1 = properties; _i < properties_1.length; _i++) {\n var property = properties_1[_i];\n var value = this.resolveValue(opts[property]);\n if (typeof value === 'string') {\n cssTextArr.push(strings.format(_CSS_MAP[property], value));\n }\n }\n return cssTextArr.length !== lenBefore;\n };\n DecorationCSSRules.prototype.resolveValue = function (value) {\n if (isThemeColor(value)) {\n this._usesThemeColors = true;\n var color = this._theme.getColor(value.id);\n if (color) {\n return color.toString();\n }\n return 'transparent';\n }\n return value;\n };\n return DecorationCSSRules;\n}());\nvar CSSNameHelper = /** @class */ (function () {\n function CSSNameHelper() {\n }\n CSSNameHelper.getClassName = function (key, type) {\n return 'ced-' + key + '-' + type;\n };\n CSSNameHelper.getSelector = function (key, parentKey, ruleType) {\n var selector = '.monaco-editor .' + this.getClassName(key, ruleType);\n if (parentKey) {\n selector = selector + '.' + this.getClassName(parentKey, ruleType);\n }\n if (ruleType === 3 /* BeforeContentClassName */) {\n selector += '::before';\n }\n else if (ruleType === 4 /* AfterContentClassName */) {\n selector += '::after';\n }\n return selector;\n };\n return CSSNameHelper;\n}());\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { windowOpenNoOpener } from '../../../base/browser/dom.js';\nimport { Schemas } from '../../../base/common/network.js';\nimport { CodeEditorServiceImpl } from '../../browser/services/codeEditorServiceImpl.js';\nvar StandaloneCodeEditorServiceImpl = /** @class */ (function (_super) {\n __extends(StandaloneCodeEditorServiceImpl, _super);\n function StandaloneCodeEditorServiceImpl() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n StandaloneCodeEditorServiceImpl.prototype.getActiveCodeEditor = function () {\n return null; // not supported in the standalone case\n };\n StandaloneCodeEditorServiceImpl.prototype.openCodeEditor = function (input, source, sideBySide) {\n if (!source) {\n return Promise.resolve(null);\n }\n return Promise.resolve(this.doOpenEditor(source, input));\n };\n StandaloneCodeEditorServiceImpl.prototype.doOpenEditor = function (editor, input) {\n var model = this.findModel(editor, input.resource);\n if (!model) {\n if (input.resource) {\n var schema = input.resource.scheme;\n if (schema === Schemas.http || schema === Schemas.https) {\n // This is a fully qualified http or https URL\n windowOpenNoOpener(input.resource.toString());\n return editor;\n }\n }\n return null;\n }\n var selection = (input.options ? input.options.selection : null);\n if (selection) {\n if (typeof selection.endLineNumber === 'number' && typeof selection.endColumn === 'number') {\n editor.setSelection(selection);\n editor.revealRangeInCenter(selection, 1 /* Immediate */);\n }\n else {\n var pos = {\n lineNumber: selection.startLineNumber,\n column: selection.startColumn\n };\n editor.setPosition(pos);\n editor.revealPositionInCenter(pos, 1 /* Immediate */);\n }\n }\n return editor;\n };\n StandaloneCodeEditorServiceImpl.prototype.findModel = function (editor, resource) {\n var model = editor.getModel();\n if (model && model.uri.toString() !== resource.toString()) {\n return null;\n }\n return model;\n };\n return StandaloneCodeEditorServiceImpl;\n}(CodeEditorServiceImpl));\nexport { StandaloneCodeEditorServiceImpl };\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport { Color } from '../../../../base/common/color.js';\nvar ParsedTokenThemeRule = /** @class */ (function () {\n function ParsedTokenThemeRule(token, index, fontStyle, foreground, background) {\n this.token = token;\n this.index = index;\n this.fontStyle = fontStyle;\n this.foreground = foreground;\n this.background = background;\n }\n return ParsedTokenThemeRule;\n}());\nexport { ParsedTokenThemeRule };\n/**\n * Parse a raw theme into rules.\n */\nexport function parseTokenTheme(source) {\n if (!source || !Array.isArray(source)) {\n return [];\n }\n var result = [], resultLen = 0;\n for (var i = 0, len = source.length; i < len; i++) {\n var entry = source[i];\n var fontStyle = -1 /* NotSet */;\n if (typeof entry.fontStyle === 'string') {\n fontStyle = 0 /* None */;\n var segments = entry.fontStyle.split(' ');\n for (var j = 0, lenJ = segments.length; j < lenJ; j++) {\n var segment = segments[j];\n switch (segment) {\n case 'italic':\n fontStyle = fontStyle | 1 /* Italic */;\n break;\n case 'bold':\n fontStyle = fontStyle | 2 /* Bold */;\n break;\n case 'underline':\n fontStyle = fontStyle | 4 /* Underline */;\n break;\n }\n }\n }\n var foreground = null;\n if (typeof entry.foreground === 'string') {\n foreground = entry.foreground;\n }\n var background = null;\n if (typeof entry.background === 'string') {\n background = entry.background;\n }\n result[resultLen++] = new ParsedTokenThemeRule(entry.token || '', i, fontStyle, foreground, background);\n }\n return result;\n}\n/**\n * Resolve rules (i.e. inheritance).\n */\nfunction resolveParsedTokenThemeRules(parsedThemeRules, customTokenColors) {\n // Sort rules lexicographically, and then by index if necessary\n parsedThemeRules.sort(function (a, b) {\n var r = strcmp(a.token, b.token);\n if (r !== 0) {\n return r;\n }\n return a.index - b.index;\n });\n // Determine defaults\n var defaultFontStyle = 0 /* None */;\n var defaultForeground = '000000';\n var defaultBackground = 'ffffff';\n while (parsedThemeRules.length >= 1 && parsedThemeRules[0].token === '') {\n var incomingDefaults = parsedThemeRules.shift();\n if (incomingDefaults.fontStyle !== -1 /* NotSet */) {\n defaultFontStyle = incomingDefaults.fontStyle;\n }\n if (incomingDefaults.foreground !== null) {\n defaultForeground = incomingDefaults.foreground;\n }\n if (incomingDefaults.background !== null) {\n defaultBackground = incomingDefaults.background;\n }\n }\n var colorMap = new ColorMap();\n // start with token colors from custom token themes\n for (var _i = 0, customTokenColors_1 = customTokenColors; _i < customTokenColors_1.length; _i++) {\n var color = customTokenColors_1[_i];\n colorMap.getId(color);\n }\n var foregroundColorId = colorMap.getId(defaultForeground);\n var backgroundColorId = colorMap.getId(defaultBackground);\n var defaults = new ThemeTrieElementRule(defaultFontStyle, foregroundColorId, backgroundColorId);\n var root = new ThemeTrieElement(defaults);\n for (var i = 0, len = parsedThemeRules.length; i < len; i++) {\n var rule = parsedThemeRules[i];\n root.insert(rule.token, rule.fontStyle, colorMap.getId(rule.foreground), colorMap.getId(rule.background));\n }\n return new TokenTheme(colorMap, root);\n}\nvar colorRegExp = /^#?([0-9A-Fa-f]{6})([0-9A-Fa-f]{2})?$/;\nvar ColorMap = /** @class */ (function () {\n function ColorMap() {\n this._lastColorId = 0;\n this._id2color = [];\n this._color2id = new Map();\n }\n ColorMap.prototype.getId = function (color) {\n if (color === null) {\n return 0;\n }\n var match = color.match(colorRegExp);\n if (!match) {\n throw new Error('Illegal value for token color: ' + color);\n }\n color = match[1].toUpperCase();\n var value = this._color2id.get(color);\n if (value) {\n return value;\n }\n value = ++this._lastColorId;\n this._color2id.set(color, value);\n this._id2color[value] = Color.fromHex('#' + color);\n return value;\n };\n ColorMap.prototype.getColorMap = function () {\n return this._id2color.slice(0);\n };\n return ColorMap;\n}());\nexport { ColorMap };\nvar TokenTheme = /** @class */ (function () {\n function TokenTheme(colorMap, root) {\n this._colorMap = colorMap;\n this._root = root;\n this._cache = new Map();\n }\n TokenTheme.createFromRawTokenTheme = function (source, customTokenColors) {\n return this.createFromParsedTokenTheme(parseTokenTheme(source), customTokenColors);\n };\n TokenTheme.createFromParsedTokenTheme = function (source, customTokenColors) {\n return resolveParsedTokenThemeRules(source, customTokenColors);\n };\n TokenTheme.prototype.getColorMap = function () {\n return this._colorMap.getColorMap();\n };\n TokenTheme.prototype._match = function (token) {\n return this._root.match(token);\n };\n TokenTheme.prototype.match = function (languageId, token) {\n // The cache contains the metadata without the language bits set.\n var result = this._cache.get(token);\n if (typeof result === 'undefined') {\n var rule = this._match(token);\n var standardToken = toStandardTokenType(token);\n result = (rule.metadata\n | (standardToken << 8 /* TOKEN_TYPE_OFFSET */)) >>> 0;\n this._cache.set(token, result);\n }\n return (result\n | (languageId << 0 /* LANGUAGEID_OFFSET */)) >>> 0;\n };\n return TokenTheme;\n}());\nexport { TokenTheme };\nvar STANDARD_TOKEN_TYPE_REGEXP = /\\b(comment|string|regex|regexp)\\b/;\nexport function toStandardTokenType(tokenType) {\n var m = tokenType.match(STANDARD_TOKEN_TYPE_REGEXP);\n if (!m) {\n return 0 /* Other */;\n }\n switch (m[1]) {\n case 'comment':\n return 1 /* Comment */;\n case 'string':\n return 2 /* String */;\n case 'regex':\n return 4 /* RegEx */;\n case 'regexp':\n return 4 /* RegEx */;\n }\n throw new Error('Unexpected match for standard token type!');\n}\nexport function strcmp(a, b) {\n if (a < b) {\n return -1;\n }\n if (a > b) {\n return 1;\n }\n return 0;\n}\nvar ThemeTrieElementRule = /** @class */ (function () {\n function ThemeTrieElementRule(fontStyle, foreground, background) {\n this._fontStyle = fontStyle;\n this._foreground = foreground;\n this._background = background;\n this.metadata = ((this._fontStyle << 11 /* FONT_STYLE_OFFSET */)\n | (this._foreground << 14 /* FOREGROUND_OFFSET */)\n | (this._background << 23 /* BACKGROUND_OFFSET */)) >>> 0;\n }\n ThemeTrieElementRule.prototype.clone = function () {\n return new ThemeTrieElementRule(this._fontStyle, this._foreground, this._background);\n };\n ThemeTrieElementRule.prototype.acceptOverwrite = function (fontStyle, foreground, background) {\n if (fontStyle !== -1 /* NotSet */) {\n this._fontStyle = fontStyle;\n }\n if (foreground !== 0 /* None */) {\n this._foreground = foreground;\n }\n if (background !== 0 /* None */) {\n this._background = background;\n }\n this.metadata = ((this._fontStyle << 11 /* FONT_STYLE_OFFSET */)\n | (this._foreground << 14 /* FOREGROUND_OFFSET */)\n | (this._background << 23 /* BACKGROUND_OFFSET */)) >>> 0;\n };\n return ThemeTrieElementRule;\n}());\nexport { ThemeTrieElementRule };\nvar ThemeTrieElement = /** @class */ (function () {\n function ThemeTrieElement(mainRule) {\n this._mainRule = mainRule;\n this._children = new Map();\n }\n ThemeTrieElement.prototype.match = function (token) {\n if (token === '') {\n return this._mainRule;\n }\n var dotIndex = token.indexOf('.');\n var head;\n var tail;\n if (dotIndex === -1) {\n head = token;\n tail = '';\n }\n else {\n head = token.substring(0, dotIndex);\n tail = token.substring(dotIndex + 1);\n }\n var child = this._children.get(head);\n if (typeof child !== 'undefined') {\n return child.match(tail);\n }\n return this._mainRule;\n };\n ThemeTrieElement.prototype.insert = function (token, fontStyle, foreground, background) {\n if (token === '') {\n // Merge into the main rule\n this._mainRule.acceptOverwrite(fontStyle, foreground, background);\n return;\n }\n var dotIndex = token.indexOf('.');\n var head;\n var tail;\n if (dotIndex === -1) {\n head = token;\n tail = '';\n }\n else {\n head = token.substring(0, dotIndex);\n tail = token.substring(dotIndex + 1);\n }\n var child = this._children.get(head);\n if (typeof child === 'undefined') {\n child = new ThemeTrieElement(this._mainRule.clone());\n this._children.set(head, child);\n }\n child.insert(tail, fontStyle, foreground, background);\n };\n return ThemeTrieElement;\n}());\nexport { ThemeTrieElement };\nexport function generateTokensCSSForColorMap(colorMap) {\n var rules = [];\n for (var i = 1, len = colorMap.length; i < len; i++) {\n var color = colorMap[i];\n rules[i] = \".mtk\" + i + \" { color: \" + color + \"; }\";\n }\n rules.push('.mtki { font-style: italic; }');\n rules.push('.mtkb { font-weight: bold; }');\n rules.push('.mtku { text-decoration: underline; text-underline-position: under; }');\n return rules.join('\\n');\n}\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nvar _a, _b, _c;\nimport { editorActiveIndentGuides, editorIndentGuides } from '../../common/view/editorColorRegistry.js';\nimport { editorBackground, editorForeground, editorInactiveSelection, editorSelectionHighlight } from '../../../platform/theme/common/colorRegistry.js';\n/* -------------------------------- Begin vs theme -------------------------------- */\nexport var vs = {\n base: 'vs',\n inherit: false,\n rules: [\n { token: '', foreground: '000000', background: 'fffffe' },\n { token: 'invalid', foreground: 'cd3131' },\n { token: 'emphasis', fontStyle: 'italic' },\n { token: 'strong', fontStyle: 'bold' },\n { token: 'variable', foreground: '001188' },\n { token: 'variable.predefined', foreground: '4864AA' },\n { token: 'constant', foreground: 'dd0000' },\n { token: 'comment', foreground: '008000' },\n { token: 'number', foreground: '09885A' },\n { token: 'number.hex', foreground: '3030c0' },\n { token: 'regexp', foreground: '800000' },\n { token: 'annotation', foreground: '808080' },\n { token: 'type', foreground: '008080' },\n { token: 'delimiter', foreground: '000000' },\n { token: 'delimiter.html', foreground: '383838' },\n { token: 'delimiter.xml', foreground: '0000FF' },\n { token: 'tag', foreground: '800000' },\n { token: 'tag.id.pug', foreground: '4F76AC' },\n { token: 'tag.class.pug', foreground: '4F76AC' },\n { token: 'meta.scss', foreground: '800000' },\n { token: 'metatag', foreground: 'e00000' },\n { token: 'metatag.content.html', foreground: 'FF0000' },\n { token: 'metatag.html', foreground: '808080' },\n { token: 'metatag.xml', foreground: '808080' },\n { token: 'metatag.php', fontStyle: 'bold' },\n { token: 'key', foreground: '863B00' },\n { token: 'string.key.json', foreground: 'A31515' },\n { token: 'string.value.json', foreground: '0451A5' },\n { token: 'attribute.name', foreground: 'FF0000' },\n { token: 'attribute.value', foreground: '0451A5' },\n { token: 'attribute.value.number', foreground: '09885A' },\n { token: 'attribute.value.unit', foreground: '09885A' },\n { token: 'attribute.value.html', foreground: '0000FF' },\n { token: 'attribute.value.xml', foreground: '0000FF' },\n { token: 'string', foreground: 'A31515' },\n { token: 'string.html', foreground: '0000FF' },\n { token: 'string.sql', foreground: 'FF0000' },\n { token: 'string.yaml', foreground: '0451A5' },\n { token: 'keyword', foreground: '0000FF' },\n { token: 'keyword.json', foreground: '0451A5' },\n { token: 'keyword.flow', foreground: 'AF00DB' },\n { token: 'keyword.flow.scss', foreground: '0000FF' },\n { token: 'operator.scss', foreground: '666666' },\n { token: 'operator.sql', foreground: '778899' },\n { token: 'operator.swift', foreground: '666666' },\n { token: 'predefined.sql', foreground: 'FF00FF' },\n ],\n colors: (_a = {},\n _a[editorBackground] = '#FFFFFE',\n _a[editorForeground] = '#000000',\n _a[editorInactiveSelection] = '#E5EBF1',\n _a[editorIndentGuides] = '#D3D3D3',\n _a[editorActiveIndentGuides] = '#939393',\n _a[editorSelectionHighlight] = '#ADD6FF4D',\n _a)\n};\n/* -------------------------------- End vs theme -------------------------------- */\n/* -------------------------------- Begin vs-dark theme -------------------------------- */\nexport var vs_dark = {\n base: 'vs-dark',\n inherit: false,\n rules: [\n { token: '', foreground: 'D4D4D4', background: '1E1E1E' },\n { token: 'invalid', foreground: 'f44747' },\n { token: 'emphasis', fontStyle: 'italic' },\n { token: 'strong', fontStyle: 'bold' },\n { token: 'variable', foreground: '74B0DF' },\n { token: 'variable.predefined', foreground: '4864AA' },\n { token: 'variable.parameter', foreground: '9CDCFE' },\n { token: 'constant', foreground: '569CD6' },\n { token: 'comment', foreground: '608B4E' },\n { token: 'number', foreground: 'B5CEA8' },\n { token: 'number.hex', foreground: '5BB498' },\n { token: 'regexp', foreground: 'B46695' },\n { token: 'annotation', foreground: 'cc6666' },\n { token: 'type', foreground: '3DC9B0' },\n { token: 'delimiter', foreground: 'DCDCDC' },\n { token: 'delimiter.html', foreground: '808080' },\n { token: 'delimiter.xml', foreground: '808080' },\n { token: 'tag', foreground: '569CD6' },\n { token: 'tag.id.pug', foreground: '4F76AC' },\n { token: 'tag.class.pug', foreground: '4F76AC' },\n { token: 'meta.scss', foreground: 'A79873' },\n { token: 'meta.tag', foreground: 'CE9178' },\n { token: 'metatag', foreground: 'DD6A6F' },\n { token: 'metatag.content.html', foreground: '9CDCFE' },\n { token: 'metatag.html', foreground: '569CD6' },\n { token: 'metatag.xml', foreground: '569CD6' },\n { token: 'metatag.php', fontStyle: 'bold' },\n { token: 'key', foreground: '9CDCFE' },\n { token: 'string.key.json', foreground: '9CDCFE' },\n { token: 'string.value.json', foreground: 'CE9178' },\n { token: 'attribute.name', foreground: '9CDCFE' },\n { token: 'attribute.value', foreground: 'CE9178' },\n { token: 'attribute.value.number.css', foreground: 'B5CEA8' },\n { token: 'attribute.value.unit.css', foreground: 'B5CEA8' },\n { token: 'attribute.value.hex.css', foreground: 'D4D4D4' },\n { token: 'string', foreground: 'CE9178' },\n { token: 'string.sql', foreground: 'FF0000' },\n { token: 'keyword', foreground: '569CD6' },\n { token: 'keyword.flow', foreground: 'C586C0' },\n { token: 'keyword.json', foreground: 'CE9178' },\n { token: 'keyword.flow.scss', foreground: '569CD6' },\n { token: 'operator.scss', foreground: '909090' },\n { token: 'operator.sql', foreground: '778899' },\n { token: 'operator.swift', foreground: '909090' },\n { token: 'predefined.sql', foreground: 'FF00FF' },\n ],\n colors: (_b = {},\n _b[editorBackground] = '#1E1E1E',\n _b[editorForeground] = '#D4D4D4',\n _b[editorInactiveSelection] = '#3A3D41',\n _b[editorIndentGuides] = '#404040',\n _b[editorActiveIndentGuides] = '#707070',\n _b[editorSelectionHighlight] = '#ADD6FF26',\n _b)\n};\n/* -------------------------------- End vs-dark theme -------------------------------- */\n/* -------------------------------- Begin hc-black theme -------------------------------- */\nexport var hc_black = {\n base: 'hc-black',\n inherit: false,\n rules: [\n { token: '', foreground: 'FFFFFF', background: '000000' },\n { token: 'invalid', foreground: 'f44747' },\n { token: 'emphasis', fontStyle: 'italic' },\n { token: 'strong', fontStyle: 'bold' },\n { token: 'variable', foreground: '1AEBFF' },\n { token: 'variable.parameter', foreground: '9CDCFE' },\n { token: 'constant', foreground: '569CD6' },\n { token: 'comment', foreground: '608B4E' },\n { token: 'number', foreground: 'FFFFFF' },\n { token: 'regexp', foreground: 'C0C0C0' },\n { token: 'annotation', foreground: '569CD6' },\n { token: 'type', foreground: '3DC9B0' },\n { token: 'delimiter', foreground: 'FFFF00' },\n { token: 'delimiter.html', foreground: 'FFFF00' },\n { token: 'tag', foreground: '569CD6' },\n { token: 'tag.id.pug', foreground: '4F76AC' },\n { token: 'tag.class.pug', foreground: '4F76AC' },\n { token: 'meta', foreground: 'D4D4D4' },\n { token: 'meta.tag', foreground: 'CE9178' },\n { token: 'metatag', foreground: '569CD6' },\n { token: 'metatag.content.html', foreground: '1AEBFF' },\n { token: 'metatag.html', foreground: '569CD6' },\n { token: 'metatag.xml', foreground: '569CD6' },\n { token: 'metatag.php', fontStyle: 'bold' },\n { token: 'key', foreground: '9CDCFE' },\n { token: 'string.key', foreground: '9CDCFE' },\n { token: 'string.value', foreground: 'CE9178' },\n { token: 'attribute.name', foreground: '569CD6' },\n { token: 'attribute.value', foreground: '3FF23F' },\n { token: 'string', foreground: 'CE9178' },\n { token: 'string.sql', foreground: 'FF0000' },\n { token: 'keyword', foreground: '569CD6' },\n { token: 'keyword.flow', foreground: 'C586C0' },\n { token: 'operator.sql', foreground: '778899' },\n { token: 'operator.swift', foreground: '909090' },\n { token: 'predefined.sql', foreground: 'FF00FF' },\n ],\n colors: (_c = {},\n _c[editorBackground] = '#000000',\n _c[editorForeground] = '#FFFFFF',\n _c[editorIndentGuides] = '#FFFFFF',\n _c[editorActiveIndentGuides] = '#FFFFFF',\n _c)\n};\n/* -------------------------------- End hc-black theme -------------------------------- */\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport * as dom from '../../../base/browser/dom.js';\nimport { Color } from '../../../base/common/color.js';\nimport { Emitter } from '../../../base/common/event.js';\nimport { TokenizationRegistry } from '../../common/modes.js';\nimport { TokenTheme, generateTokensCSSForColorMap } from '../../common/modes/supports/tokenization.js';\nimport { hc_black, vs, vs_dark } from '../common/themes.js';\nimport { Registry } from '../../../platform/registry/common/platform.js';\nimport { Extensions } from '../../../platform/theme/common/colorRegistry.js';\nimport { Extensions as ThemingExtensions } from '../../../platform/theme/common/themeService.js';\nvar VS_THEME_NAME = 'vs';\nvar VS_DARK_THEME_NAME = 'vs-dark';\nvar HC_BLACK_THEME_NAME = 'hc-black';\nvar colorRegistry = Registry.as(Extensions.ColorContribution);\nvar themingRegistry = Registry.as(ThemingExtensions.ThemingContribution);\nvar StandaloneTheme = /** @class */ (function () {\n function StandaloneTheme(name, standaloneThemeData) {\n this.themeData = standaloneThemeData;\n var base = standaloneThemeData.base;\n if (name.length > 0) {\n this.id = base + ' ' + name;\n this.themeName = name;\n }\n else {\n this.id = base;\n this.themeName = base;\n }\n this.colors = null;\n this.defaultColors = Object.create(null);\n this._tokenTheme = null;\n }\n Object.defineProperty(StandaloneTheme.prototype, \"base\", {\n get: function () {\n return this.themeData.base;\n },\n enumerable: true,\n configurable: true\n });\n StandaloneTheme.prototype.notifyBaseUpdated = function () {\n if (this.themeData.inherit) {\n this.colors = null;\n this._tokenTheme = null;\n }\n };\n StandaloneTheme.prototype.getColors = function () {\n if (!this.colors) {\n var colors = Object.create(null);\n for (var id in this.themeData.colors) {\n colors[id] = Color.fromHex(this.themeData.colors[id]);\n }\n if (this.themeData.inherit) {\n var baseData = getBuiltinRules(this.themeData.base);\n for (var id in baseData.colors) {\n if (!colors[id]) {\n colors[id] = Color.fromHex(baseData.colors[id]);\n }\n }\n }\n this.colors = colors;\n }\n return this.colors;\n };\n StandaloneTheme.prototype.getColor = function (colorId, useDefault) {\n var color = this.getColors()[colorId];\n if (color) {\n return color;\n }\n if (useDefault !== false) {\n return this.getDefault(colorId);\n }\n return undefined;\n };\n StandaloneTheme.prototype.getDefault = function (colorId) {\n var color = this.defaultColors[colorId];\n if (color) {\n return color;\n }\n color = colorRegistry.resolveDefaultColor(colorId, this);\n this.defaultColors[colorId] = color;\n return color;\n };\n StandaloneTheme.prototype.defines = function (colorId) {\n return Object.prototype.hasOwnProperty.call(this.getColors(), colorId);\n };\n Object.defineProperty(StandaloneTheme.prototype, \"type\", {\n get: function () {\n switch (this.base) {\n case VS_THEME_NAME: return 'light';\n case HC_BLACK_THEME_NAME: return 'hc';\n default: return 'dark';\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(StandaloneTheme.prototype, \"tokenTheme\", {\n get: function () {\n if (!this._tokenTheme) {\n var rules = [];\n var encodedTokensColors = [];\n if (this.themeData.inherit) {\n var baseData = getBuiltinRules(this.themeData.base);\n rules = baseData.rules;\n if (baseData.encodedTokensColors) {\n encodedTokensColors = baseData.encodedTokensColors;\n }\n }\n rules = rules.concat(this.themeData.rules);\n if (this.themeData.encodedTokensColors) {\n encodedTokensColors = this.themeData.encodedTokensColors;\n }\n this._tokenTheme = TokenTheme.createFromRawTokenTheme(rules, encodedTokensColors);\n }\n return this._tokenTheme;\n },\n enumerable: true,\n configurable: true\n });\n return StandaloneTheme;\n}());\nfunction isBuiltinTheme(themeName) {\n return (themeName === VS_THEME_NAME\n || themeName === VS_DARK_THEME_NAME\n || themeName === HC_BLACK_THEME_NAME);\n}\nfunction getBuiltinRules(builtinTheme) {\n switch (builtinTheme) {\n case VS_THEME_NAME:\n return vs;\n case VS_DARK_THEME_NAME:\n return vs_dark;\n case HC_BLACK_THEME_NAME:\n return hc_black;\n }\n}\nfunction newBuiltInTheme(builtinTheme) {\n var themeData = getBuiltinRules(builtinTheme);\n return new StandaloneTheme(builtinTheme, themeData);\n}\nvar StandaloneThemeServiceImpl = /** @class */ (function () {\n function StandaloneThemeServiceImpl() {\n this.environment = Object.create(null);\n this._onThemeChange = new Emitter();\n this._onIconThemeChange = new Emitter();\n this._knownThemes = new Map();\n this._knownThemes.set(VS_THEME_NAME, newBuiltInTheme(VS_THEME_NAME));\n this._knownThemes.set(VS_DARK_THEME_NAME, newBuiltInTheme(VS_DARK_THEME_NAME));\n this._knownThemes.set(HC_BLACK_THEME_NAME, newBuiltInTheme(HC_BLACK_THEME_NAME));\n this._styleElement = dom.createStyleSheet();\n this._styleElement.className = 'monaco-colors';\n this.setTheme(VS_THEME_NAME);\n }\n Object.defineProperty(StandaloneThemeServiceImpl.prototype, \"onThemeChange\", {\n get: function () {\n return this._onThemeChange.event;\n },\n enumerable: true,\n configurable: true\n });\n StandaloneThemeServiceImpl.prototype.defineTheme = function (themeName, themeData) {\n if (!/^[a-z0-9\\-]+$/i.test(themeName)) {\n throw new Error('Illegal theme name!');\n }\n if (!isBuiltinTheme(themeData.base) && !isBuiltinTheme(themeName)) {\n throw new Error('Illegal theme base!');\n }\n // set or replace theme\n this._knownThemes.set(themeName, new StandaloneTheme(themeName, themeData));\n if (isBuiltinTheme(themeName)) {\n this._knownThemes.forEach(function (theme) {\n if (theme.base === themeName) {\n theme.notifyBaseUpdated();\n }\n });\n }\n if (this._theme && this._theme.themeName === themeName) {\n this.setTheme(themeName); // refresh theme\n }\n };\n StandaloneThemeServiceImpl.prototype.getTheme = function () {\n return this._theme;\n };\n StandaloneThemeServiceImpl.prototype.setTheme = function (themeName) {\n var _this = this;\n var theme;\n if (this._knownThemes.has(themeName)) {\n theme = this._knownThemes.get(themeName);\n }\n else {\n theme = this._knownThemes.get(VS_THEME_NAME);\n }\n if (this._theme === theme) {\n // Nothing to do\n return theme.id;\n }\n this._theme = theme;\n var cssRules = [];\n var hasRule = {};\n var ruleCollector = {\n addRule: function (rule) {\n if (!hasRule[rule]) {\n cssRules.push(rule);\n hasRule[rule] = true;\n }\n }\n };\n themingRegistry.getThemingParticipants().forEach(function (p) { return p(theme, ruleCollector, _this.environment); });\n var tokenTheme = theme.tokenTheme;\n var colorMap = tokenTheme.getColorMap();\n ruleCollector.addRule(generateTokensCSSForColorMap(colorMap));\n this._styleElement.innerHTML = cssRules.join('\\n');\n TokenizationRegistry.setColorMap(colorMap);\n this._onThemeChange.fire(theme);\n return theme.id;\n };\n StandaloneThemeServiceImpl.prototype.getIconTheme = function () {\n return {\n hasFileIcons: false,\n hasFolderIcons: false,\n hidesExplorerArrows: false\n };\n };\n return StandaloneThemeServiceImpl;\n}());\nexport { StandaloneThemeServiceImpl };\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nvar __param = (this && this.__param) || function (paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n};\nimport { Event, PauseableEmitter } from '../../../base/common/event.js';\nimport { dispose } from '../../../base/common/lifecycle.js';\nimport { keys } from '../../../base/common/map.js';\nimport { CommandsRegistry } from '../../commands/common/commands.js';\nimport { IConfigurationService } from '../../configuration/common/configuration.js';\nimport { IContextKeyService, SET_CONTEXT_COMMAND_ID } from '../common/contextkey.js';\nimport { KeybindingResolver } from '../../keybinding/common/keybindingResolver.js';\nvar KEYBINDING_CONTEXT_ATTR = 'data-keybinding-context';\nvar Context = /** @class */ (function () {\n function Context(id, parent) {\n this._id = id;\n this._parent = parent;\n this._value = Object.create(null);\n this._value['_contextId'] = id;\n }\n Context.prototype.setValue = function (key, value) {\n // console.log('SET ' + key + ' = ' + value + ' ON ' + this._id);\n if (this._value[key] !== value) {\n this._value[key] = value;\n return true;\n }\n return false;\n };\n Context.prototype.removeValue = function (key) {\n // console.log('REMOVE ' + key + ' FROM ' + this._id);\n if (key in this._value) {\n delete this._value[key];\n return true;\n }\n return false;\n };\n Context.prototype.getValue = function (key) {\n var ret = this._value[key];\n if (typeof ret === 'undefined' && this._parent) {\n return this._parent.getValue(key);\n }\n return ret;\n };\n return Context;\n}());\nexport { Context };\nvar NullContext = /** @class */ (function (_super) {\n __extends(NullContext, _super);\n function NullContext() {\n return _super.call(this, -1, null) || this;\n }\n NullContext.prototype.setValue = function (key, value) {\n return false;\n };\n NullContext.prototype.removeValue = function (key) {\n return false;\n };\n NullContext.prototype.getValue = function (key) {\n return undefined;\n };\n NullContext.INSTANCE = new NullContext();\n return NullContext;\n}(Context));\nvar ConfigAwareContextValuesContainer = /** @class */ (function (_super) {\n __extends(ConfigAwareContextValuesContainer, _super);\n function ConfigAwareContextValuesContainer(id, _configurationService, emitter) {\n var _this = _super.call(this, id, null) || this;\n _this._configurationService = _configurationService;\n _this._values = new Map();\n _this._listener = _this._configurationService.onDidChangeConfiguration(function (event) {\n if (event.source === 6 /* DEFAULT */) {\n // new setting, reset everything\n var allKeys = keys(_this._values);\n _this._values.clear();\n emitter.fire(new ArrayContextKeyChangeEvent(allKeys));\n }\n else {\n var changedKeys = [];\n for (var _i = 0, _a = event.affectedKeys; _i < _a.length; _i++) {\n var configKey = _a[_i];\n var contextKey = \"config.\" + configKey;\n if (_this._values.has(contextKey)) {\n _this._values.delete(contextKey);\n changedKeys.push(contextKey);\n }\n }\n emitter.fire(new ArrayContextKeyChangeEvent(changedKeys));\n }\n });\n return _this;\n }\n ConfigAwareContextValuesContainer.prototype.dispose = function () {\n this._listener.dispose();\n };\n ConfigAwareContextValuesContainer.prototype.getValue = function (key) {\n if (key.indexOf(ConfigAwareContextValuesContainer._keyPrefix) !== 0) {\n return _super.prototype.getValue.call(this, key);\n }\n if (this._values.has(key)) {\n return this._values.get(key);\n }\n var configKey = key.substr(ConfigAwareContextValuesContainer._keyPrefix.length);\n var configValue = this._configurationService.getValue(configKey);\n var value = undefined;\n switch (typeof configValue) {\n case 'number':\n case 'boolean':\n case 'string':\n value = configValue;\n break;\n }\n this._values.set(key, value);\n return value;\n };\n ConfigAwareContextValuesContainer.prototype.setValue = function (key, value) {\n return _super.prototype.setValue.call(this, key, value);\n };\n ConfigAwareContextValuesContainer.prototype.removeValue = function (key) {\n return _super.prototype.removeValue.call(this, key);\n };\n ConfigAwareContextValuesContainer._keyPrefix = 'config.';\n return ConfigAwareContextValuesContainer;\n}(Context));\nvar ContextKey = /** @class */ (function () {\n function ContextKey(service, key, defaultValue) {\n this._service = service;\n this._key = key;\n this._defaultValue = defaultValue;\n this.reset();\n }\n ContextKey.prototype.set = function (value) {\n this._service.setContext(this._key, value);\n };\n ContextKey.prototype.reset = function () {\n if (typeof this._defaultValue === 'undefined') {\n this._service.removeContext(this._key);\n }\n else {\n this._service.setContext(this._key, this._defaultValue);\n }\n };\n ContextKey.prototype.get = function () {\n return this._service.getContextKeyValue(this._key);\n };\n return ContextKey;\n}());\nvar SimpleContextKeyChangeEvent = /** @class */ (function () {\n function SimpleContextKeyChangeEvent(key) {\n this.key = key;\n }\n SimpleContextKeyChangeEvent.prototype.affectsSome = function (keys) {\n return keys.has(this.key);\n };\n return SimpleContextKeyChangeEvent;\n}());\nvar ArrayContextKeyChangeEvent = /** @class */ (function () {\n function ArrayContextKeyChangeEvent(keys) {\n this.keys = keys;\n }\n ArrayContextKeyChangeEvent.prototype.affectsSome = function (keys) {\n for (var _i = 0, _a = this.keys; _i < _a.length; _i++) {\n var key = _a[_i];\n if (keys.has(key)) {\n return true;\n }\n }\n return false;\n };\n return ArrayContextKeyChangeEvent;\n}());\nvar CompositeContextKeyChangeEvent = /** @class */ (function () {\n function CompositeContextKeyChangeEvent(events) {\n this.events = events;\n }\n CompositeContextKeyChangeEvent.prototype.affectsSome = function (keys) {\n for (var _i = 0, _a = this.events; _i < _a.length; _i++) {\n var e = _a[_i];\n if (e.affectsSome(keys)) {\n return true;\n }\n }\n return false;\n };\n return CompositeContextKeyChangeEvent;\n}());\nvar AbstractContextKeyService = /** @class */ (function () {\n function AbstractContextKeyService(myContextId) {\n this._onDidChangeContext = new PauseableEmitter({ merge: function (input) { return new CompositeContextKeyChangeEvent(input); } });\n this._isDisposed = false;\n this._myContextId = myContextId;\n }\n AbstractContextKeyService.prototype.createKey = function (key, defaultValue) {\n if (this._isDisposed) {\n throw new Error(\"AbstractContextKeyService has been disposed\");\n }\n return new ContextKey(this, key, defaultValue);\n };\n Object.defineProperty(AbstractContextKeyService.prototype, \"onDidChangeContext\", {\n get: function () {\n return this._onDidChangeContext.event;\n },\n enumerable: true,\n configurable: true\n });\n AbstractContextKeyService.prototype.bufferChangeEvents = function (callback) {\n this._onDidChangeContext.pause();\n try {\n callback();\n }\n finally {\n this._onDidChangeContext.resume();\n }\n };\n AbstractContextKeyService.prototype.createScoped = function (domNode) {\n if (this._isDisposed) {\n throw new Error(\"AbstractContextKeyService has been disposed\");\n }\n return new ScopedContextKeyService(this, domNode);\n };\n AbstractContextKeyService.prototype.contextMatchesRules = function (rules) {\n if (this._isDisposed) {\n throw new Error(\"AbstractContextKeyService has been disposed\");\n }\n var context = this.getContextValuesContainer(this._myContextId);\n var result = KeybindingResolver.contextMatchesRules(context, rules);\n // console.group(rules.serialize() + ' -> ' + result);\n // rules.keys().forEach(key => { console.log(key, ctx[key]); });\n // console.groupEnd();\n return result;\n };\n AbstractContextKeyService.prototype.getContextKeyValue = function (key) {\n if (this._isDisposed) {\n return undefined;\n }\n return this.getContextValuesContainer(this._myContextId).getValue(key);\n };\n AbstractContextKeyService.prototype.setContext = function (key, value) {\n if (this._isDisposed) {\n return;\n }\n var myContext = this.getContextValuesContainer(this._myContextId);\n if (!myContext) {\n return;\n }\n if (myContext.setValue(key, value)) {\n this._onDidChangeContext.fire(new SimpleContextKeyChangeEvent(key));\n }\n };\n AbstractContextKeyService.prototype.removeContext = function (key) {\n if (this._isDisposed) {\n return;\n }\n if (this.getContextValuesContainer(this._myContextId).removeValue(key)) {\n this._onDidChangeContext.fire(new SimpleContextKeyChangeEvent(key));\n }\n };\n AbstractContextKeyService.prototype.getContext = function (target) {\n if (this._isDisposed) {\n return NullContext.INSTANCE;\n }\n return this.getContextValuesContainer(findContextAttr(target));\n };\n return AbstractContextKeyService;\n}());\nexport { AbstractContextKeyService };\nvar ContextKeyService = /** @class */ (function (_super) {\n __extends(ContextKeyService, _super);\n function ContextKeyService(configurationService) {\n var _this = _super.call(this, 0) || this;\n _this._contexts = new Map();\n _this._toDispose = [];\n _this._lastContextId = 0;\n var myContext = new ConfigAwareContextValuesContainer(_this._myContextId, configurationService, _this._onDidChangeContext);\n _this._contexts.set(_this._myContextId, myContext);\n _this._toDispose.push(myContext);\n return _this;\n // Uncomment this to see the contexts continuously logged\n // let lastLoggedValue: string | null = null;\n // setInterval(() => {\n // \tlet values = Object.keys(this._contexts).map((key) => this._contexts[key]);\n // \tlet logValue = values.map(v => JSON.stringify(v._value, null, '\\t')).join('\\n');\n // \tif (lastLoggedValue !== logValue) {\n // \t\tlastLoggedValue = logValue;\n // \t\tconsole.log(lastLoggedValue);\n // \t}\n // }, 2000);\n }\n ContextKeyService.prototype.dispose = function () {\n this._isDisposed = true;\n this._toDispose = dispose(this._toDispose);\n };\n ContextKeyService.prototype.getContextValuesContainer = function (contextId) {\n if (this._isDisposed) {\n return NullContext.INSTANCE;\n }\n return this._contexts.get(contextId) || NullContext.INSTANCE;\n };\n ContextKeyService.prototype.createChildContext = function (parentContextId) {\n if (parentContextId === void 0) { parentContextId = this._myContextId; }\n if (this._isDisposed) {\n throw new Error(\"ContextKeyService has been disposed\");\n }\n var id = (++this._lastContextId);\n this._contexts.set(id, new Context(id, this.getContextValuesContainer(parentContextId)));\n return id;\n };\n ContextKeyService.prototype.disposeContext = function (contextId) {\n if (!this._isDisposed) {\n this._contexts.delete(contextId);\n }\n };\n ContextKeyService = __decorate([\n __param(0, IConfigurationService)\n ], ContextKeyService);\n return ContextKeyService;\n}(AbstractContextKeyService));\nexport { ContextKeyService };\nvar ScopedContextKeyService = /** @class */ (function (_super) {\n __extends(ScopedContextKeyService, _super);\n function ScopedContextKeyService(parent, domNode) {\n var _this = _super.call(this, parent.createChildContext()) || this;\n _this._parent = parent;\n if (domNode) {\n _this._domNode = domNode;\n _this._domNode.setAttribute(KEYBINDING_CONTEXT_ATTR, String(_this._myContextId));\n }\n return _this;\n }\n ScopedContextKeyService.prototype.dispose = function () {\n this._isDisposed = true;\n this._parent.disposeContext(this._myContextId);\n if (this._domNode) {\n this._domNode.removeAttribute(KEYBINDING_CONTEXT_ATTR);\n this._domNode = undefined;\n }\n };\n Object.defineProperty(ScopedContextKeyService.prototype, \"onDidChangeContext\", {\n get: function () {\n return Event.any(this._parent.onDidChangeContext, this._onDidChangeContext.event);\n },\n enumerable: true,\n configurable: true\n });\n ScopedContextKeyService.prototype.getContextValuesContainer = function (contextId) {\n if (this._isDisposed) {\n return NullContext.INSTANCE;\n }\n return this._parent.getContextValuesContainer(contextId);\n };\n ScopedContextKeyService.prototype.createChildContext = function (parentContextId) {\n if (parentContextId === void 0) { parentContextId = this._myContextId; }\n if (this._isDisposed) {\n throw new Error(\"ScopedContextKeyService has been disposed\");\n }\n return this._parent.createChildContext(parentContextId);\n };\n ScopedContextKeyService.prototype.disposeContext = function (contextId) {\n if (this._isDisposed) {\n return;\n }\n this._parent.disposeContext(contextId);\n };\n return ScopedContextKeyService;\n}(AbstractContextKeyService));\nfunction findContextAttr(domNode) {\n while (domNode) {\n if (domNode.hasAttribute(KEYBINDING_CONTEXT_ATTR)) {\n var attr = domNode.getAttribute(KEYBINDING_CONTEXT_ATTR);\n if (attr) {\n return parseInt(attr, 10);\n }\n return NaN;\n }\n domNode = domNode.parentElement;\n }\n return 0;\n}\nCommandsRegistry.registerCommand(SET_CONTEXT_COMMAND_ID, function (accessor, contextKey, contextValue) {\n accessor.get(IContextKeyService).createKey(String(contextKey), contextValue);\n});\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport './menu.css';\nimport * as nls from '../../../../nls.js';\nimport * as strings from '../../../common/strings.js';\nimport { Action } from '../../../common/actions.js';\nimport { ActionBar, Separator, ActionItem, BaseActionItem } from '../actionbar/actionbar.js';\nimport { addClass, EventType, EventHelper, removeTabIndexAndUpdateFocus, isAncestor, hasClass, addDisposableListener, removeClass, append, $, addClasses, removeClasses } from '../../dom.js';\nimport { StandardKeyboardEvent } from '../../keyboardEvent.js';\nimport { RunOnceScheduler } from '../../../common/async.js';\nimport { dispose } from '../../../common/lifecycle.js';\nimport { DomScrollableElement } from '../scrollbar/scrollableElement.js';\nimport { Emitter } from '../../../common/event.js';\nimport { isLinux } from '../../../common/platform.js';\nfunction createMenuMnemonicRegExp() {\n try {\n return new RegExp('\\\\(&([^\\\\s&])\\\\)|(? 1) {\n var action = actions_1.shift();\n if (action) {\n _this.focusItemByElement(action.container);\n actions_1.push(action);\n }\n _this.mnemonics.set(key, actions_1);\n }\n }\n }));\n }\n if (isLinux) {\n _this._register(addDisposableListener(menuElement, EventType.KEY_DOWN, function (e) {\n var event = new StandardKeyboardEvent(e);\n if (event.equals(14 /* Home */) || event.equals(11 /* PageUp */)) {\n _this.focusedItem = _this.items.length - 1;\n _this.focusNext();\n EventHelper.stop(e, true);\n }\n else if (event.equals(13 /* End */) || event.equals(12 /* PageDown */)) {\n _this.focusedItem = 0;\n _this.focusPrevious();\n EventHelper.stop(e, true);\n }\n }));\n }\n _this._register(addDisposableListener(_this.domNode, EventType.MOUSE_OUT, function (e) {\n var relatedTarget = e.relatedTarget;\n if (!isAncestor(relatedTarget, _this.domNode)) {\n _this.focusedItem = undefined;\n _this.scrollTopHold = _this.menuElement.scrollTop;\n _this.updateFocus();\n e.stopPropagation();\n }\n }));\n _this._register(addDisposableListener(_this.domNode, EventType.MOUSE_UP, function (e) {\n // Absorb clicks in menu dead space https://github.com/Microsoft/vscode/issues/63575\n EventHelper.stop(e, true);\n }));\n _this._register(addDisposableListener(_this.actionsList, EventType.MOUSE_OVER, function (e) {\n var target = e.target;\n if (!target || !isAncestor(target, _this.actionsList) || target === _this.actionsList) {\n return;\n }\n while (target.parentElement !== _this.actionsList && target.parentElement !== null) {\n target = target.parentElement;\n }\n if (hasClass(target, 'action-item')) {\n var lastFocusedItem = _this.focusedItem;\n _this.scrollTopHold = _this.menuElement.scrollTop;\n _this.setFocusedItem(target);\n if (lastFocusedItem !== _this.focusedItem) {\n _this.updateFocus();\n }\n }\n }));\n var parentData = {\n parent: _this\n };\n _this.mnemonics = new Map();\n _this.push(actions, { icon: true, label: true, isMenu: true });\n // Scroll Logic\n _this.scrollableElement = _this._register(new DomScrollableElement(menuElement, {\n alwaysConsumeMouseWheel: true,\n horizontal: 2 /* Hidden */,\n vertical: 3 /* Visible */,\n verticalScrollbarSize: 7,\n handleMouseWheel: true,\n useShadows: true\n }));\n var scrollElement = _this.scrollableElement.getDomNode();\n scrollElement.style.position = null;\n menuElement.style.maxHeight = Math.max(10, window.innerHeight - container.getBoundingClientRect().top - 30) + \"px\";\n _this.scrollableElement.onScroll(function () {\n _this._onScroll.fire();\n }, _this, _this.menuDisposables);\n _this._register(addDisposableListener(_this.menuElement, EventType.SCROLL, function (e) {\n if (_this.scrollTopHold !== undefined) {\n _this.menuElement.scrollTop = _this.scrollTopHold;\n _this.scrollTopHold = undefined;\n }\n _this.scrollableElement.scanDomNode();\n }));\n container.appendChild(_this.scrollableElement.getDomNode());\n _this.scrollableElement.scanDomNode();\n _this.items.filter(function (item) { return !(item instanceof MenuSeparatorActionItem); }).forEach(function (item, index, array) {\n item.updatePositionInSet(index + 1, array.length);\n });\n return _this;\n }\n Menu.prototype.style = function (style) {\n var container = this.getContainer();\n var fgColor = style.foregroundColor ? \"\" + style.foregroundColor : null;\n var bgColor = style.backgroundColor ? \"\" + style.backgroundColor : null;\n var border = style.borderColor ? \"2px solid \" + style.borderColor : null;\n var shadow = style.shadowColor ? \"0 2px 4px \" + style.shadowColor : null;\n container.style.border = border;\n this.domNode.style.color = fgColor;\n this.domNode.style.backgroundColor = bgColor;\n container.style.boxShadow = shadow;\n if (this.items) {\n this.items.forEach(function (item) {\n if (item instanceof MenuActionItem || item instanceof MenuSeparatorActionItem) {\n item.style(style);\n }\n });\n }\n };\n Menu.prototype.getContainer = function () {\n return this.scrollableElement.getDomNode();\n };\n Object.defineProperty(Menu.prototype, \"onScroll\", {\n get: function () {\n return this._onScroll.event;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Menu.prototype, \"scrollOffset\", {\n get: function () {\n return this.menuElement.scrollTop;\n },\n enumerable: true,\n configurable: true\n });\n Menu.prototype.focusItemByElement = function (element) {\n var lastFocusedItem = this.focusedItem;\n this.setFocusedItem(element);\n if (lastFocusedItem !== this.focusedItem) {\n this.updateFocus();\n }\n };\n Menu.prototype.setFocusedItem = function (element) {\n for (var i = 0; i < this.actionsList.children.length; i++) {\n var elem = this.actionsList.children[i];\n if (element === elem) {\n this.focusedItem = i;\n break;\n }\n }\n };\n Menu.prototype.doGetActionItem = function (action, options, parentData) {\n if (action instanceof Separator) {\n return new MenuSeparatorActionItem(options.context, action, { icon: true });\n }\n else if (action instanceof SubmenuAction) {\n var menuActionItem = new SubmenuActionItem(action, action.entries, parentData, options);\n if (options.enableMnemonics) {\n var mnemonic = menuActionItem.getMnemonic();\n if (mnemonic && menuActionItem.isEnabled()) {\n var actionItems = [];\n if (this.mnemonics.has(mnemonic)) {\n actionItems = this.mnemonics.get(mnemonic);\n }\n actionItems.push(menuActionItem);\n this.mnemonics.set(mnemonic, actionItems);\n }\n }\n return menuActionItem;\n }\n else {\n var menuItemOptions = { enableMnemonics: options.enableMnemonics };\n if (options.getKeyBinding) {\n var keybinding = options.getKeyBinding(action);\n if (keybinding) {\n var keybindingLabel = keybinding.getLabel();\n if (keybindingLabel) {\n menuItemOptions.keybinding = keybindingLabel;\n }\n }\n }\n var menuActionItem = new MenuActionItem(options.context, action, menuItemOptions);\n if (options.enableMnemonics) {\n var mnemonic = menuActionItem.getMnemonic();\n if (mnemonic && menuActionItem.isEnabled()) {\n var actionItems = [];\n if (this.mnemonics.has(mnemonic)) {\n actionItems = this.mnemonics.get(mnemonic);\n }\n actionItems.push(menuActionItem);\n this.mnemonics.set(mnemonic, actionItems);\n }\n }\n return menuActionItem;\n }\n };\n return Menu;\n}(ActionBar));\nexport { Menu };\nvar MenuActionItem = /** @class */ (function (_super) {\n __extends(MenuActionItem, _super);\n function MenuActionItem(ctx, action, options) {\n if (options === void 0) { options = {}; }\n var _this = this;\n options.isMenu = true;\n _this = _super.call(this, action, action, options) || this;\n _this.options = options;\n _this.options.icon = options.icon !== undefined ? options.icon : false;\n _this.options.label = options.label !== undefined ? options.label : true;\n _this.cssClass = '';\n // Set mnemonic\n if (_this.options.label && options.enableMnemonics) {\n var label = _this.getAction().label;\n if (label) {\n var matches = MENU_MNEMONIC_REGEX.exec(label);\n if (matches) {\n _this.mnemonic = (!!matches[1] ? matches[1] : matches[2]).toLocaleLowerCase();\n }\n }\n }\n return _this;\n }\n MenuActionItem.prototype.render = function (container) {\n var _this = this;\n _super.prototype.render.call(this, container);\n if (!this.element) {\n return;\n }\n this.container = container;\n this.item = append(this.element, $('a.action-menu-item'));\n if (this._action.id === Separator.ID) {\n // A separator is a presentation item\n this.item.setAttribute('role', 'presentation');\n }\n else {\n this.item.setAttribute('role', 'menuitem');\n if (this.mnemonic) {\n this.item.setAttribute('aria-keyshortcuts', \"\" + this.mnemonic);\n }\n }\n this.check = append(this.item, $('span.menu-item-check'));\n this.check.setAttribute('role', 'none');\n this.label = append(this.item, $('span.action-label'));\n if (this.options.label && this.options.keybinding) {\n append(this.item, $('span.keybinding')).textContent = this.options.keybinding;\n }\n this._register(addDisposableListener(this.element, EventType.MOUSE_UP, function (e) {\n EventHelper.stop(e, true);\n _this.onClick(e);\n }));\n this.updateClass();\n this.updateLabel();\n this.updateTooltip();\n this.updateEnabled();\n this.updateChecked();\n };\n MenuActionItem.prototype.blur = function () {\n _super.prototype.blur.call(this);\n this.applyStyle();\n };\n MenuActionItem.prototype.focus = function () {\n _super.prototype.focus.call(this);\n this.item.focus();\n this.applyStyle();\n };\n MenuActionItem.prototype.updatePositionInSet = function (pos, setSize) {\n this.item.setAttribute('aria-posinset', \"\" + pos);\n this.item.setAttribute('aria-setsize', \"\" + setSize);\n };\n MenuActionItem.prototype.updateLabel = function () {\n if (this.options.label) {\n var label = this.getAction().label;\n if (label) {\n var cleanLabel = cleanMnemonic(label);\n if (!this.options.enableMnemonics) {\n label = cleanLabel;\n }\n this.label.setAttribute('aria-label', cleanLabel.replace(/&&/g, '&'));\n var matches = MENU_MNEMONIC_REGEX.exec(label);\n if (matches) {\n label = strings.escape(label).replace(MENU_ESCAPED_MNEMONIC_REGEX, '